"use client";

import { Fragment, useEffect, useMemo, useState } from "react";
import type { GroupSummary } from "@/types/group";
import { fetchDailyG } from "@/lib/api";
import RenderUnifiedData from "./RenderUnifiedData";

const mapping_name: Record<string, string> = {
  site: "سایت",
  digi: "دیجی",
  snapp: "اسنپ",
  express: "اکسپرس",
  nextDay: "نکست دی",
  tapsiExpress: "تپسی اکسپرس",
  techno: "تکنو",
  digiMassnoat: "مصنوعات دیجی",
};

const replicateByTypes = (items: GroupSummary[]) => {
  const todeli: GroupSummary[] = [];
  const postpack: GroupSummary[] = [];
  const factor: GroupSummary[] = [];
  const shemsh: GroupSummary[] = [];

  const types = ["تودلی", "پست پک", "فاکتور", "پرینت شمش"];

  items.forEach((item) => {
    const mappedParent = mapping_name[item.parent] || item.parent;

    todeli.push({
      ...item,
      type: types[0],
      key: `${mappedParent}|${item.group_name}|${types[0]}`,
    });

    if (
      !(
        ["digi", "snapp", "digiMassnoat"].includes(item.parent) &&
        ![
          "سعدی",
          "دراپ شیپینگ زربن",
          "مصنوعات",
          "مروا",
          "زرین",
          "دراپ شیپینگ مروا",
          "دراپ شیپینگ سعدی",
          "امیریان",
          "زهیری",
        ].includes(item.group_name)
      )
    ) {
      postpack.push({
        ...item,
        type: types[1],
        key: `${mappedParent}|${item.group_name}|${types[1]}`,
      });
    }

    factor.push({
      ...item,
      type: types[2],
      key: `${mappedParent}|${item.group_name}|${types[2]}`,
    });

    if (item.group_name === "شمش[-]") {
      shemsh.push({
        ...item,
        type: types[3],
        key: `${mappedParent}|${item.group_name}|${types[3]}`,
      });
    }
  });

  return { todeli, postpack, factor, shemsh };
};

const TYPE_LABELS = ["تودلی", "پست پک", "فاکتور", "پرینت شمش"] as const;
type TypeKey = (typeof TYPE_LABELS)[number];

interface PrintCategoriesProps {
  todayJalali: number;
}

interface UnifiedData {
  labelParts: string[];
  items: Partial<Record<TypeKey, GroupSummary>>;
  group: string;
}

const PrintCategories: React.FC<PrintCategoriesProps> = ({ todayJalali }) => {
  const [todeli, setTodeli] = useState<GroupSummary[]>([]);
  const [postpack, setPostpack] = useState<GroupSummary[]>([]);
  const [factor, setFactor] = useState<GroupSummary[]>([]);
  const [shemsh, setShemsh] = useState<GroupSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadDailyG = async () => {
      try {
        setLoading(true);
        setError(null);
        const json = await fetchDailyG();
        // API returns [[{parent, group_name, objects_row_index, count, ...}, ...]]
        const data = json[0];
        if (Array.isArray(data) && data.length > 0) {
          const replicated = replicateByTypes(data);
          setTodeli(replicated.todeli);
          setPostpack(replicated.postpack);
          setFactor(replicated.factor);
          setShemsh(replicated.shemsh);
        }
      } catch (err) {
        console.error("Failed to load daily_g", err);
        setError("خطا در دریافت اطلاعات. لطفاً دوباره تلاش کنید.");
      } finally {
        setLoading(false);
      }
    };
    loadDailyG();
  }, []);

  const unifiedData = useMemo(() => {
    const map = new Map<string, UnifiedData>();

    [...todeli, ...postpack, ...factor, ...shemsh].forEach((item) => {
      const baseKey = `${item.parent}|${item.group_name}`;
      if (!map.has(baseKey)) {
        map.set(baseKey, {
          labelParts: [
            mapping_name[item.parent] || item.parent,
            item.group_name,
          ],
          items: {},
          group:
            mapping_name[item.parent] +
            "---" +
            item.group_name.replace(/\[.*?\]/g, ""),
        });
      }
      map.get(baseKey)!.items[item.type as TypeKey] = item;
    });

    return Array.from(map.values());
  }, [todeli, postpack, factor, shemsh]);

  const groupedData = useMemo<Record<string, UnifiedData[]>>(() => {
    return unifiedData.reduce<Record<string, UnifiedData[]>>((acc, item) => {
      const key = item.group;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item);
      return acc;
    }, {});
  }, [unifiedData]);

  const handleCopy = (rowIndexes: number[]) => {
    navigator.clipboard.writeText(rowIndexes.sort((a, b) => a - b).join(","));
  };

  if (loading) {
    return (
      <div className="text-center py-8 text-lg text-slate-500 dark:text-slate-400">
        در حال دریافت اطلاعات...
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <p className="text-lg text-red-500 mb-4">{error}</p>
        <button
          onClick={() => window.location.reload()}
          className="px-4 py-2 rounded-md border border-amber-300 text-slate-600 hover:bg-slate-200 dark:border-amber-600 dark:text-slate-300 dark:hover:bg-slate-600 transition"
        >
          تلاش مجدد
        </button>
      </div>
    );
  }

  if (Object.keys(groupedData).length === 0) {
    return (
      <div className="text-center py-8 text-lg text-slate-500 dark:text-slate-400">
        داده‌ای یافت نشد.
      </div>
    );
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
        <thead className="bg-slate-200 text-slate-700 dark:bg-slate-700 dark:text-slate-200 sticky top-0">
          <tr>
            <th className="px-3 py-2 text-right">نام</th>
            <th className="px-3 py-2">ردیف چاپ</th>
            <th className="px-3 py-2">اتمام چاپ</th>
            <th className="px-3 py-2">تعداد</th>
            {TYPE_LABELS.map((t) => (
              <th key={t} className="px-3 py-2">
                {t}
              </th>
            ))}
          </tr>
        </thead>
        {Object.entries(groupedData).map(([groupName, items]) => {
          let rows: number[] = [];
          items.forEach((item) => {
            const data = Object.values(item.items).find((x) => x) as
              | GroupSummary
              | undefined;
            if (data) {
              rows.push(...data.objects_row_index);
            }
          });
          return (
            <Fragment key={groupName}>
              <hr className="text-amber-500" />
              <div className="flex justify-between">
                <div className="m-2 text-white">{groupName}</div>
                <button
                  onClick={() => rows && handleCopy(rows)}
                  className="m-2 rounded-md border px-2 py-1 text-xs border-amber-300 text-slate-600 hover:bg-slate-200 dark:border-amber-600 dark:text-slate-300 dark:hover:bg-slate-600 transition"
                >
                  کپی همه
                </button>
              </div>
              <tbody className="divide-y dark:divide-slate-700">
                {items ? (
                  <RenderUnifiedData
                    unifiedData={items}
                    todayJalali={todayJalali}
                  />
                ) : null}
              </tbody>
            </Fragment>
          );
        })}
      </table>
    </div>
  );
};

export default PrintCategories;
