import Button from "@/components/Forms/Button";
import Input from "@/components/Forms/Input";
import {
  Table,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import React, { useEffect, useState } from "react";

interface MenuItem {
  id_aba_card: string;
  abas: MenuItem[];
  nome_aba_card: string;
}

const TabelaAbasCard = ({
  form,
  defaultValues,
  abas,
  storageKey,
  letra,
}: any) => {
  const [mobileView, setMobileView] = useState(false);

  const [abasId, setAbasId] = useState<any[]>(() => {
    const storageAbas = localStorage.getItem(storageKey);
    if (storageAbas) {
      return JSON.parse(storageAbas);
    } else if (defaultValues && defaultValues["permissoes_abas_card"]) {
      return defaultValues["permissoes_abas_card"]
        .split("^")
        .filter((item: string) => item !== "");
    } else {
      return [];
    }
  });

  useEffect(() => {
    form.setValue("permissoes_abas_card", abasId.join("^"));
    localStorage.setItem(storageKey, JSON.stringify(abasId));
  }, [abasId]);

  useEffect(() => {
    const windowSize = window.innerWidth;
    setMobileView(windowSize < 640);
  }, []);

  return (
    <>
      <Table className="min-w-full bg-white dark:bg-[#1d2a39] border border-gray-300 shadow-sm">
        <TableHeader>
          <TableRow>
            <TableHead className="font-bold py-2 px-4 border-b text-center">
              Menu
            </TableHead>
            <TableHead className="w-6 font-bold">Acesso</TableHead>
          </TableRow>
        </TableHeader>
        <tbody>
          <TableRow>
            <TableCell className="py-2 text-center ">
              <div className="mx-auto flex flex-row gap-2">
                <Button
                  type="button"
                  className="bg-meta-1 flex-1 py-1 px-2 text-sm"
                  onClick={() => {
                    setAbasId([]); // Limpa todos os IDs
                  }}
                >
                  Desmarcar Todas
                </Button>
                <Button
                  type="button"
                  className="flex-1 py-1 px-2 text-sm"
                  onClick={() => {
                    setAbasId(
                      abas
                        .map((aba: any) => aba.id_aba_card) // IDs principais
                        .concat(
                          abas.flatMap((aba: any) =>
                            aba.abas
                              ? aba.abas.map((a: any) => a.id_aba_card)
                              : []
                          )
                        )
                    );
                  }}
                >
                  Marcar Todas
                </Button>
              </div>
            </TableCell>
            <TableCell className="py-2 text-center"></TableCell>
          </TableRow>
          {abas?.map((aba: any, index: number) => (
            <React.Fragment key={aba.id_aba_card}>
              <TableRow>
                <TableCell className="py-2 text-left">
                  {letra
                    ? `${letra}${index + 1}. ${aba.nome_aba_card}`
                    : aba.nome_aba_card}
                </TableCell>
                <TableCell className="py-2 text-center">
                  <Input
                    checked={abasId.some((id) => id === aba.id_aba_card)}
                    type="checkbox"
                    onChange={(e) => {
                      if (e.target.checked) {
                        setAbasId((previous) => [...previous, aba.id_aba_card]);
                      } else {
                        setAbasId((previous) =>
                          previous.filter(
                            (abaFiltro) => abaFiltro !== aba.id_aba_card
                          )
                        );
                      }
                    }}
                  />
                </TableCell>
              </TableRow>
            </React.Fragment>
          ))}
        </tbody>
      </Table>
    </>
  );
};

export default TabelaAbasCard;
