import { Grid } from "../../components/Grid/Grid";
import { useApiRequest } from "../../utils/useApiRequest";
import { motion, AnimatePresence } from "framer-motion";
import { useState } from "react";
import {
  BuildingOfficeIcon,
  ChevronRightIcon,
  CalendarIcon,
  UserIcon,
  DocumentTextIcon,
  TruckIcon,
} from "@heroicons/react/24/outline";
import { formatJustDate } from "../../utils/formatTime";

const formatWeight = (value: number | string | undefined, unit?: string) => {
  if (value === null || value === undefined || value === "") return "-";
  const num =
    typeof value === "number" ? value : Number(String(value).replace(/,/g, ""));
  const formatted = Number.isNaN(num)
    ? value
    : Intl.NumberFormat("fa-IR").format(num);
  return `${formatted} ${unit || ""}`.trim();
};

const DistributionNode = ({
  item,
  code,
  level = 0,
  isLast = false,
  parentPath = [],
}: {
  item: any;
  code: string;
  level?: number;
  isLast?: boolean;
  parentPath?: boolean[];
}) => {
  const [isExpanded, setIsExpanded] = useState(level === 0);
  const [isWarehouseEntriesExpanded, setIsWarehouseEntriesExpanded] =
    useState(false);
  const shouldFetchChildren = item?.assigned_organization?.is_distributor > 0;

  const { data: childrenData, isLoading } = useApiRequest({
    api: `/product/web/api/v1/quota_distribution/quota_distributions_assigned_by_org/?org_id=${item?.assigned_organization?.id}&quota_id=${code}`,
    method: "get",
    queryKey: ["distributions_overview", item?.assigned_organization?.id, code],
    enabled: shouldFetchChildren && isExpanded,
  });

  const { data: warehouseEntriesData, isLoading: isLoadingWarehouseEntries } =
    useApiRequest({
      api: `/warehouse/web/api/v1/inventory_entry/${code}/my_entries_by_quota/?org_id=${item?.assigned_organization?.id}`,
      method: "get",
      queryKey: ["warehouse_entries", item?.assigned_organization?.id, code],
      enabled: isWarehouseEntriesExpanded && !!item?.assigned_organization?.id,
    });

  const hasChildren =
    shouldFetchChildren &&
    childrenData?.results &&
    childrenData.results.length > 0;

  const indentWidth = 20;

  return (
    <div className="relative">
      <div
        className="flex items-start gap-2"
        style={{ paddingRight: `${level * indentWidth}px` }}
      >
        <div className="flex-1 min-w-0">
          <motion.div
            initial={{ opacity: 0, x: -10 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.2, delay: level * 0.02 }}
            className="group relative"
          >
            <div className="flex items-start gap-2 p-3 rounded-lg border border-gray-200/60 bg-white/50 backdrop-blur-sm hover:bg-white hover:border-gray-300 hover:shadow-sm transition-all dark:border-gray-700/60 dark:bg-gray-800/50 dark:hover:bg-gray-800 dark:hover:border-gray-600">
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between gap-2 mb-1">
                  <div className="flex items-center gap-1.5 min-w-0 flex-1">
                    <div className="flex-shrink-0 w-5 h-5 rounded-md bg-gradient-to-br from-primary-500 to-primary-600 flex items-center justify-center shadow-sm">
                      <BuildingOfficeIcon className="h-3 w-3 text-white" />
                    </div>
                    <div className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                      {item?.assigned_organization?.organization || "نامشخص"}
                    </div>
                  </div>
                  {shouldFetchChildren && (
                    <button
                      onClick={() => setIsExpanded(!isExpanded)}
                      className="flex-shrink-0 w-5 h-5 rounded-md flex items-center justify-center text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors dark:text-gray-300 dark:hover:text-primary-400 dark:hover:bg-primary-900/30"
                    >
                      <motion.div
                        animate={{ rotate: isExpanded ? 90 : 0 }}
                        transition={{ duration: 0.15 }}
                      >
                        <ChevronRightIcon className="h-3 w-3" />
                      </motion.div>
                    </button>
                  )}
                </div>

                <div className="flex items-center flex-wrap gap-2 mb-1 text-xs text-gray-500 dark:text-gray-200">
                  {item?.create_date && (
                    <span className="flex items-center gap-0.5">
                      <CalendarIcon className="h-3 w-3" />
                      {formatJustDate(item.create_date)}
                    </span>
                  )}
                  {item?.distribution_id && (
                    <span className="flex items-center gap-0.5">
                      <DocumentTextIcon className="h-3 w-3" />
                      {item.distribution_id}
                    </span>
                  )}
                  {item?.assigner_organization && (
                    <span className="flex items-center gap-0.5">
                      <UserIcon className="h-3 w-3" />
                      <span className="truncate">
                        {item.assigner_organization.organization}
                        {item?.creator_info && ` (${item.creator_info})`}
                      </span>
                    </span>
                  )}
                </div>

                <div className="flex flex-wrap gap-2 mb-1">
                  <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-primary-50 text-primary-700 dark:bg-primary-900/30 dark:text-primary-200">
                    وزن: {formatWeight(item?.weight, item?.sale_unit?.unit)}
                  </span>
                  <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-200">
                    فروش: {formatWeight(item?.been_sold, item?.sale_unit?.unit)}
                  </span>
                  <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200">
                    مانده:{" "}
                    {formatWeight(
                      item?.warehouse_balance,
                      item?.sale_unit?.unit
                    )}
                  </span>
                  <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-200">
                    ورودی:{" "}
                    {formatWeight(item?.warehouse_entry, item?.sale_unit?.unit)}
                  </span>
                  {item?.description && (
                    <div className="px-1.5 py-0.5 rounded text-xs text-gray-600 bg-gray-50/80 dark:bg-gray-700/40 dark:text-gray-100 mb-1">
                      {item.description}
                    </div>
                  )}
                </div>

                {item?.assigned_organization?.id && (
                  <div className="mt-0.5">
                    <button
                      onClick={() =>
                        setIsWarehouseEntriesExpanded(
                          !isWarehouseEntriesExpanded
                        )
                      }
                      className="w-full flex items-center justify-between px-1.5 py-1 rounded text-xs text-gray-600 bg-gray-50 hover:bg-gray-100 transition-colors dark:bg-gray-700/40 dark:text-gray-100 dark:hover:bg-gray-700/60"
                    >
                      <div className="flex items-center gap-1">
                        <TruckIcon className="h-3.5 w-3.5" />
                        <span>ورودی به انبار</span>
                        {warehouseEntriesData?.results &&
                          warehouseEntriesData.results.length > 0 && (
                            <span className="px-1 py-0.5 rounded-full bg-primary-100 text-primary-700 text-[10px] font-medium dark:bg-primary-900/50 dark:text-primary-200">
                              {warehouseEntriesData.results.length}
                            </span>
                          )}
                      </div>
                      <motion.div
                        animate={{
                          rotate: isWarehouseEntriesExpanded ? 180 : 0,
                        }}
                        transition={{ duration: 0.15 }}
                      >
                        <ChevronRightIcon className="h-3 w-3" />
                      </motion.div>
                    </button>

                    <AnimatePresence>
                      {isWarehouseEntriesExpanded && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: "auto" }}
                          exit={{ opacity: 0, height: 0 }}
                          transition={{ duration: 0.15 }}
                          className="mt-0.5 space-y-1"
                        >
                          {isLoadingWarehouseEntries && (
                            <div className="px-2 py-1 rounded text-xs text-gray-500 dark:text-gray-200 flex items-center gap-1.5">
                              <motion.div
                                animate={{ rotate: 360 }}
                                transition={{
                                  duration: 1,
                                  repeat: Infinity,
                                  ease: "linear",
                                }}
                                className="w-2 h-2 rounded-full border-2 border-primary-500 border-t-transparent"
                              />
                              در حال بارگذاری
                            </div>
                          )}

                          {!isLoadingWarehouseEntries &&
                            warehouseEntriesData?.results &&
                            warehouseEntriesData.results.length > 0 &&
                            warehouseEntriesData.results.map(
                              (entry: any, index: number) => (
                                <motion.div
                                  key={index}
                                  initial={{ opacity: 0, x: -5 }}
                                  animate={{ opacity: 1, x: 0 }}
                                  transition={{ delay: index * 0.02 }}
                                  className="px-2 py-1 rounded border border-gray-200 bg-white text-xs text-gray-900 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
                                >
                                  <div className="flex flex-col gap-2">
                                    <div className="flex items-center flex-wrap gap-1.5">
                                      <span className="inline-flex items-center px-1.5 py-0.5 rounded bg-primary-50 text-primary-700 text-xs dark:bg-primary-900/30 dark:text-primary-200">
                                        وزن:{" "}
                                        {formatWeight(
                                          entry?.weight,
                                          item?.sale_unit?.unit
                                        )}
                                      </span>
                                      {entry?.lading_number && (
                                        <span className="flex items-center gap-0.5 text-gray-600 dark:text-gray-200 text-xs">
                                          <DocumentTextIcon className="h-3 w-3" />
                                          <span>
                                            بارنامه: {entry.lading_number}
                                          </span>
                                        </span>
                                      )}
                                    </div>
                                    {entry?.delivery_address && (
                                      <div className="text-gray-600 dark:text-gray-200 text-xs">
                                        <span className="font-medium">
                                          محل دریافت:{" "}
                                        </span>
                                        <span>{entry.delivery_address}</span>
                                      </div>
                                    )}
                                    {entry?.notes && (
                                      <div className="px-1.5 py-0.5 rounded text-[11px] text-gray-600 bg-gray-50 dark:bg-gray-700/40 dark:text-gray-100">
                                        {entry.notes}
                                      </div>
                                    )}
                                  </div>
                                </motion.div>
                              )
                            )}

                          {!isLoadingWarehouseEntries &&
                            (!warehouseEntriesData?.results ||
                              warehouseEntriesData.results.length === 0) && (
                              <div className="px-2 py-1 rounded text-xs text-gray-400 dark:text-gray-300">
                                ورودی به انبار ثبت نشده است
                              </div>
                            )}
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                )}
              </div>
            </div>
          </motion.div>

          <AnimatePresence>
            {isExpanded && hasChildren && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: "auto" }}
                exit={{ opacity: 0, height: 0 }}
                transition={{ duration: 0.2 }}
                className="mt-1"
              >
                <div className="space-y-1.5">
                  {childrenData.results.map((child: any, index: number) => (
                    <DistributionNode
                      key={child.id || index}
                      item={child}
                      code={code}
                      level={level + 1}
                      isLast={index === childrenData.results.length - 1}
                      parentPath={[...parentPath, !isLast]}
                    />
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {isExpanded && isLoading && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="mt-1 px-2 py-1 rounded text-xs text-gray-500 dark:text-gray-200 flex items-center gap-1.5"
              style={{ paddingRight: `${(level + 1) * indentWidth + 8}px` }}
            >
              <motion.div
                animate={{ rotate: 360 }}
                transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                className="w-2 h-2 rounded-full border-2 border-primary-500 border-t-transparent"
              />
              در حال بارگذاری
            </motion.div>
          )}

          {isExpanded &&
            shouldFetchChildren &&
            !isLoading &&
            (!childrenData?.results || childrenData.results.length === 0) && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="mt-1 px-2 py-1 rounded text-xs text-gray-400 dark:text-gray-300"
                style={{ paddingRight: `${(level + 1) * indentWidth + 8}px` }}
              >
                توزیع دیگری ثبت نشده است
              </motion.div>
            )}
        </div>
      </div>
    </div>
  );
};

export const QuotaDistributionOverview = ({
  item,
  code,
}: {
  item: any;
  getData: () => void;
  code: string;
}) => {
  return (
    <Grid container column className="gap-2">
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.2 }}
        className="w-full"
      >
        <DistributionNode item={item} code={code} level={0} />
      </motion.div>
    </Grid>
  );
};
