"use client";

import { Fragment, useEffect, useState } from "react";
import type { GroupSummary } from "@/types/group";
import CompletePrint from "./CompletePrint";
import { fetchCheckboxes, saveCheckboxes, status2print } from "@/lib/api";

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

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

interface RenderUnifiedProps {
  unifiedData: UnifiedData[];
  todayJalali: number;
}

const RenderUnifiedData = ({
  unifiedData,
  todayJalali,
}: RenderUnifiedProps) => {
  const [checkboxState, setCheckboxState] = useState<Record<string, boolean>>(
    {}
  );

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

  const handleDone = (rowIndexes: number[]) => {
    status2print(rowIndexes);
  };

  useEffect(() => {
    const loadCheckboxes = async () => {
      try {
        const json = await fetchCheckboxes(todayJalali);
        if (json?.[0]?.jalali_date === todayJalali) {
          setCheckboxState(json[0].data);
        }
      } catch (err) {
        console.error("Failed to load checkboxes", err);
      }
    };
    loadCheckboxes();
  }, [todayJalali]);

  useEffect(() => {
    if (!Object.keys(checkboxState).length) return;
    saveCheckboxes(todayJalali, checkboxState);
  }, [checkboxState, todayJalali]);

  return (
    <Fragment>
      {unifiedData.map((row, idx) => {
        const firstItem = Object.values(row.items).find((x) => x) as
          | GroupSummary
          | undefined;

        return (
          <tr
            key={idx}
            className={`transition ${
              firstItem && checkboxState[firstItem.key]
                ? "bg-emerald-100 dark:bg-emerald-900/40"
                : "hover:bg-slate-100 dark:hover:bg-slate-700/40"
            }`}
          >
            <td className="px-1 py-1 text-right font-sm w-max text-slate-700 dark:text-slate-200">
              {row.labelParts.map((name) => {
                const hue =
                  Array.from(name).reduce(
                    (acc, char) => acc + char.charCodeAt(0),
                    0
                  ) % 360;
                const borderColor = `hsl(${hue}, 40%, 20%)`;
                return (
                  <span
                    key={name}
                    className="w-max px-1 py-1 rounded-lg text-md font-semibold m-1 backdrop-blur-sm backdrop-opacity-10 bg-white/10 border-1"
                    style={{ borderColor }}
                  >
                    {name}
                  </span>
                );
              })}
            </td>

            <td className="px-3 py-2 text-center">
              <button
                onClick={() =>
                  firstItem && handleCopy(firstItem.objects_row_index)
                }
                className="rounded-md border px-2 py-1 text-xs border-slate-300 text-slate-600 hover:bg-slate-200 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-600 transition"
              >
                کپی
              </button>
            </td>

            <td className="px-3 py-2 text-center">
              <CompletePrint
                onClick={() =>
                  firstItem && handleDone(firstItem.objects_row_index)
                }
              />
            </td>

            <td className="px-3 py-2 text-center font-semibold text-slate-600 dark:text-slate-300">
              {firstItem?.objects_row_index.length || 0}
            </td>

            {TYPE_LABELS.map((type) => {
              const item = row.items[type];
              if (!item) {
                return (
                  <td key={type} className="text-center text-slate-400">
                    —
                  </td>
                );
              }
              return (
                <td key={type} className="px-3 py-2 text-center">
                  <input
                    type="checkbox"
                    checked={!!checkboxState[item.key]}
                    onChange={() =>
                      setCheckboxState((prev) => ({
                        ...prev,
                        [item.key]: !prev[item.key],
                      }))
                    }
                    className="w-4 h-4 accent-emerald-600 cursor-pointer"
                  />
                </td>
              );
            })}
          </tr>
        );
      })}
    </Fragment>
  );
};

export default RenderUnifiedData;
