import React, { useState, useEffect, useMemo, useRef } from "react";
import { Card } from "../../tremor/Card";
import { Title, Text } from "../../tremor/Text";
import { Input } from "../../tremor/Input";
import { Logo } from "../../components/Logo/Logo";
import { useBackend } from "../Wrapper";
import { useTheme } from "../Dashboard/useTheme";
import { Dashboard } from "../Dashboard/Dashboard";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { ClockIcon, PencilIcon, TableCellsIcon, LinkIcon } from "@heroicons/react/24/outline";
import { PresentationChartBarIcon } from "@heroicons/react/24/solid";
dayjs.extend(relativeTime);

const DashboardCard: React.FC<{
  dashboard: any;
  onClick?: (dashboard: any) => void;
  variant?: "list" | "grid";
}> = ({ dashboard, onClick, variant = "grid" }) => {
  return (
    <Card
      onClick={() => onClick && onClick(dashboard)}
      className={
        "onvo-dashboard-card !onvo-p-4 onvo-cursor-pointer onvo-gap-4 onvo-flex " +
        (variant === "grid"
          ? "onvo-flex-col"
          : "onvo-flex-row onvo-items-center")
      }
    >

      <div className="onvo-flex onvo-flex-grow onvo-flex-row onvo-items-center onvo-gap-4">

        {dashboard.thumbnail && dashboard.thumbnail.trim() !== "" ? (
          <div
            className={
              "onvo-relative onvo-h-12 onvo-w-12 onvo-flex-shrink-0 onvo-rounded-xl onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900"
            }
          >
            <img
              src={dashboard.thumbnail || ""}
              alt={dashboard.title}
              className="onvo-rounded-xl onvo-bg-slate-50 onvo-h-full onvo-w-full onvo-object-contain dark:onvo-bg-slate-900"
            />
          </div>
        ) : (
          <div className="onvo-h-12 onvo-w-12 onvo-flex-shrink-0 onvo-rounded-xl onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
            <PresentationChartBarIcon className="onvo-w-6 onvo-h-6 onvo-text-slate-400 dark:onvo-text-slate-500" />
          </div>
        )}
        <div className="onvo-flex-grow">
          <Title className="onvo-default-font onvo-dashboard-card-title">{dashboard.title}</Title>
          <Text className="onvo-default-font onvo-dashboard-card-description">
            {dashboard.description}
          </Text>
        </div>
      </div>

      <div className="onvo-grid onvo-grid-cols-2">
        <div className="onvo-w-36 onvo-flex-shrink-0 onvo-flex onvo-flex-col onvo-gap-1">
          <Text className="onvo-default-font onvo-dashboard-card-details-text onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
            <TableCellsIcon height={16} width={16} /> {dashboard._meta.widgets}{" "}
            widgets
          </Text>
          <Text className="onvo-default-font onvo-dashboard-card-details-text onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
            <LinkIcon height={16} width={16} /> {dashboard._meta.datasources}{" "}
            datasources
          </Text>
        </div>
        <div className="onvo-w-48 onvo-flex-shrink-0 onvo-flex onvo-flex-col onvo-gap-1">
          <Text className="onvo-default-font onvo-dashboard-card-details-text onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
            <ClockIcon height={16} width={16} />
            Created {dayjs(dashboard.created_at).fromNow()}
          </Text>
          <Text className="onvo-default-font onvo-dashboard-card-details-text onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
            <PencilIcon height={16} width={16} />
            Updated {dayjs(dashboard.last_updated_at).fromNow()}
          </Text>
        </div>
      </div>
    </Card>
  );
};

export const DashboardList: React.FC<{
  onClickItem?: (dashboard: any) => void;
  variant?: "list" | "grid";
  title?: string;
  theme?: "light" | "dark" | "system";
  layout?: "default" | "sidebar" | "tabs";
}> = ({
  onClickItem,
  variant = "grid",
  title = "Dashboards",
  theme: themeProp = "system",
  layout = "default",
}) => {
    const [dashboards, setDashboards] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const { backend, team } = useBackend();
    const theme = useTheme(themeProp);
    const [search, setSearch] = useState("");
    const [selectedDashboard, setSelectedDashboard] = useState<any>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const [containerHeight, setContainerHeight] = useState<number>(0);

    console.log("THEME: ", theme);

    useEffect(() => {
      if (backend) {
        setLoading(true);
        backend.dashboards
          .list()
          .then((a) => {
            // @ts-ignore
            setDashboards(a);
            if (a.length > 0) {
              setSelectedDashboard(a[0]);
            }
            setLoading(false);
          })
          .catch((e) => {
            setLoading(false);
          });
      }
    }, [backend]);

    useEffect(() => {
      const updateHeight = () => {
        if (containerRef.current && containerRef.current.parentElement) {
          const parentHeight = containerRef.current.parentElement.offsetHeight;
          setContainerHeight(parentHeight);
        }
      };

      // Use setTimeout to ensure DOM is fully rendered
      const timer = setTimeout(updateHeight, 100);
      window.addEventListener('resize', updateHeight);

      return () => {
        clearTimeout(timer);
        window.removeEventListener('resize', updateHeight);
      };
    }, []);

    const filtered = useMemo(() => {
      return (
        search === ""
          ? dashboards
          : dashboards.filter((a) => {
            return (a.id + " " + a.title + " " + a.description)
              .toLowerCase()
              .includes(search.toLowerCase());
          })
      )
    }, [dashboards, search]);


    return (
      <div ref={containerRef} className="onvo-w-full onvo-max-w-full onvo-h-full">
        {layout === "default" ? (
          <div className="onvo-relative onvo-h-full onvo-flex onvo-flex-col onvo-bg-slate-100 dark:onvo-bg-slate-900 onvo-p-4 onvo-bg-opacity-100">
            <div className="onvo-mb-3 onvo-flex onvo-flex-row onvo-items-center onvo-justify-between">
              <div className="onvo-flex onvo-items-center onvo-gap-2">
                {team?.logo ? (
                  <div className="onvo-h-8 onvo-w-8 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                    <img src={team.logo as any} alt={team?.name || "Team"} className="onvo-h-6 onvo-w-6 onvo-object-contain" />
                  </div>
                ) : (
                  <div className="onvo-h-8 onvo-w-8 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                    <Logo className="onvo-h-5 onvo-w-5" />
                  </div>
                )}
                <Title className="onvo-default-font !onvo-text-2xl">{title}</Title>
              </div>
              <Input
                type="search"
                placeholder="Search"
                className="onvo-max-w-96"
                inputClassName="onvo-default-font"
                onChange={(e) => setSearch(e.target.value)}
              />
            </div>
            <div
              className={
                "onvo-dashboard-list onvo-w-full onvo-flex-1 onvo-overflow-auto " +
                (variant === "grid"
                  ? "onvo-grid onvo-gap-4 onvo-grid-cols-1 md:onvo-grid-cols-2 xl:onvo-grid-cols-3 onvo-auto-rows-auto onvo-items-start onvo-content-start onvo-place-items-start onvo-place-content-start"
                  : "onvo-flex onvo-flex-col onvo-gap-4")
              }
            >
              {filtered.map((a) => (
                <DashboardCard
                  key={a.id}
                  dashboard={a}
                  onClick={onClickItem}
                  variant={variant}
                />
              ))}
            </div>
          </div>
        ) : layout === "sidebar" ? (
          <div className="onvo-flex onvo-h-full onvo-bg-slate-100 dark:onvo-bg-slate-900 onvo-bg-opacity-100">
            <div className="onvo-w-64 onvo-flex-shrink-0 onvo-bg-slate-100 dark:onvo-bg-slate-900 onvo-shadow-lg onvo-border-r onvo-border-slate-200 dark:onvo-border-slate-700 onvo-flex onvo-flex-col onvo-h-full">
              <div className="onvo-px-6 onvo-pt-4 onvo-pb-2 onvo-flex-shrink-0">
                <div className="onvo-flex onvo-items-center onvo-gap-2 onvo-pb-2 onvo-pt-1">
                  {team?.logo ? (
                    <div className="onvo-h-8 onvo-w-8 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                      <img src={team.logo as any} alt={team?.name || "Team"} className="onvo-h-6 onvo-w-6 onvo-object-contain" />
                    </div>
                  ) : (
                    <div className="onvo-h-8 onvo-w-8 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                      <Logo className="onvo-h-5 onvo-w-5" />
                    </div>
                  )}
                  <Title className="onvo-default-font !onvo-text-2xl">{title}</Title>
                </div>
                <Input
                  type="search"
                  placeholder="Search"
                  className="onvo-mb-2"
                  inputClassName="onvo-default-font"
                  onChange={(e) => setSearch(e.target.value)}
                />
              </div>
              <nav className="onvo-space-y-2 onvo-px-6 onvo-pb-4 onvo-flex-1 onvo-overflow-y-auto">
                {filtered.map((dashboard) => (
                  <button
                    key={dashboard.id}
                    onClick={() => {
                      setSelectedDashboard(dashboard);
                      if (onClickItem) onClickItem(dashboard);
                    }}
                    className={`onvo-default-font onvo-w-full onvo-text-left onvo-px-2 onvo-py-2 onvo-rounded-lg onvo-transition-colors onvo-truncate ${selectedDashboard?.id === dashboard.id
                      ? "onvo-bg-blue-100 dark:onvo-bg-blue-900 onvo-text-blue-700 dark:onvo-text-blue-300"
                      : "onvo-text-slate-600 dark:onvo-text-slate-300 hover:onvo-bg-slate-100 dark:hover:onvo-bg-slate-700"
                      }`}
                    title={dashboard.title}
                  >
                    <span className="onvo-default-font onvo-flex onvo-items-center onvo-gap-2 onvo-truncate">
                      {dashboard.thumbnail && dashboard.thumbnail.trim() !== "" ? (
                        <div className="onvo-h-8 onvo-w-8 onvo-flex-shrink-0 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900">
                          <img
                            src={dashboard.thumbnail || ""}
                            alt={dashboard.title}
                            className="onvo-rounded-lg onvo-h-full onvo-w-full onvo-object-contain"
                          />
                        </div>
                      ) : (
                        <div className="onvo-h-8 onvo-w-8 onvo-flex-shrink-0 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                          <PresentationChartBarIcon className="onvo-w-4 onvo-h-4 onvo-text-slate-400 dark:onvo-text-slate-500" />
                        </div>
                      )}
                      <span className="onvo-default-font onvo-truncate">{dashboard.title}</span>
                    </span>
                  </button>
                ))}
              </nav>
            </div>

            <div className="onvo-flex-1 onvo-overflow-y-auto onvo-min-w-0">
              {selectedDashboard ? (
                <Dashboard id={selectedDashboard.id} className="onvo-max-w-full" />
              ) : (
                <div className="onvo-flex onvo-items-center onvo-justify-center onvo-h-96">
                  <div className="onvo-text-slate-500 dark:onvo-text-slate-400">
                    Select a dashboard to view
                  </div>
                </div>
              )}
            </div>
          </div>
        ) : (
          <div className="onvo-flex onvo-flex-col onvo-h-full onvo-bg-slate-100 dark:onvo-bg-slate-900 onvo-bg-opacity-100">
            <div className="onvo-flex-shrink-0 onvo-bg-slate-100 dark:onvo-bg-slate-900 onvo-shadow-sm onvo-border-b onvo-border-slate-200 dark:onvo-border-slate-700">
              <div className="onvo-w-full onvo-px-6">
                <div className="onvo-pt-4">
                  <div className="onvo-flex onvo-flex-row onvo-items-center onvo-justify-between onvo-mb-2">
                    <div className="onvo-flex onvo-items-center onvo-gap-2">
                      {team?.logo ? (
                        <div className="onvo-h-8 onvo-w-8 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                          <img src={team.logo as any} alt={team?.name || "Team"} className="onvo-h-6 onvo-w-6 onvo-object-contain" />
                        </div>
                      ) : (
                        <div className="onvo-h-8 onvo-w-8 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-flex onvo-items-center onvo-justify-center">
                          <Logo className="onvo-h-5 onvo-w-5" />
                        </div>
                      )}
                      <Title className="!onvo-text-2xl">{title}</Title>
                    </div>
                    <Input
                      type="search"
                      placeholder="Search"
                      className="onvo-max-w-96"
                      onChange={(e) => setSearch(e.target.value)}
                    />
                  </div>
                  <div className="onvo-flex onvo-space-x-8 onvo-overflow-x-auto">
                    {filtered.map((dashboard) => (
                      <button
                        key={dashboard.id}
                        onClick={() => {
                          setSelectedDashboard(dashboard);
                          if (onClickItem) onClickItem(dashboard);
                        }}
                        className={`onvo-pb-2 onvo-px-1 onvo-border-b-2 onvo-font-medium onvo-text-sm onvo-transition-colors onvo-whitespace-nowrap ${selectedDashboard?.id === dashboard.id
                          ? "onvo-border-blue-500 onvo-text-blue-600 dark:onvo-text-blue-400"
                          : "onvo-border-transparent onvo-text-slate-500 dark:onvo-text-slate-400 hover:onvo-text-slate-700 dark:hover:onvo-text-slate-300 hover:onvo-border-slate-300"
                          }`}
                      >
                        <span className="onvo-inline-flex onvo-items-center onvo-gap-2 onvo-truncate">
                          {dashboard.thumbnail && dashboard.thumbnail.trim() !== "" ? (
                            <span className="onvo-inline-flex onvo-h-8 onvo-w-8 onvo-flex-shrink-0 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900">
                              <img
                                src={dashboard.thumbnail || ""}
                                alt={dashboard.title}
                                className="onvo-rounded-lg onvo-h-full onvo-w-full onvo-object-contain"
                              />
                            </span>
                          ) : (
                            <span className="onvo-inline-flex onvo-h-8 onvo-w-8 onvo-flex-shrink-0 onvo-rounded-lg onvo-border onvo-border-slate-200 onvo-bg-slate-50 dark:onvo-border-slate-700 dark:onvo-bg-slate-900 onvo-items-center onvo-justify-center">
                              <PresentationChartBarIcon className="onvo-w-4 onvo-h-4 onvo-text-slate-400 dark:onvo-text-slate-500" />
                            </span>
                          )}
                          <span className="onvo-truncate">{dashboard.title}</span>
                        </span>
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="onvo-flex-1 onvo-overflow-y-auto">
              {selectedDashboard ? (
                <Dashboard id={selectedDashboard.id} className="onvo-max-w-full" />
              ) : (
                <div className="onvo-flex onvo-items-center onvo-justify-center onvo-h-96">
                  <div className="onvo-text-slate-500 dark:onvo-text-slate-400">
                    Select a dashboard to view
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };
