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

const TabelaGraficos = ({ defaultValues, form, graficos, letra }: any) => {
  const [graficosDefault, setGraficosDefault] = useState(
    form?.control?._formValues["permissoes_graficos_perfil"] ||
      (defaultValues ? defaultValues["permissoes_graficos_perfil"] : ""),
  );
  const [graficosId, setGraficosId] = useState<any[]>(
    graficosDefault ? graficosDefault.split("^") : [],
  );

  useEffect(() => {
    if (graficosId.length === graficos.length) {
      form.setValue("permissoes_graficos_perfil", "all");
      setGraficosDefault("all");
    } else {
      form.setValue("permissoes_graficos_perfil", graficosId.join("^"));
      setGraficosDefault(graficosId.join("^"));
    }
  }, [graficosId]);

  let mostraGraficos = false;

  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">
            Visualização dos Gráficos
          </TableHead>
          <TableHead className="w-6 font-bold">Visualizar</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={() => {
                  setGraficosId([]);
                }}
              >
                Desmarcar Todos Gráficos
              </Button>
              <Button
                type="button"
                className="flex-1 py-1 px-2 text-sm"
                onClick={() => {
                  setGraficosId(
                    graficos
                      .map((grafico: any) => grafico.id_grafico)
                      .concat(
                        graficos.map((grafico: any) =>
                          grafico.graficos?.map(
                            (subgrafico: any) => subgrafico.id_grafico,
                          ),
                        ),
                      )
                      .flat(),
                  );
                }}
              >
                Marcar Todos Gráficos
              </Button>
            </div>
          </TableCell>
        </TableRow>
        {graficos?.map((grafico: any, index: number) => {
          if (graficosId.includes("all")) {
            mostraGraficos = true;
          } else {
            mostraGraficos = graficosId.some((id) => id === grafico.id_grafico);
          }
          return (
            <TableRow key={grafico.id_grafico}>
              <TableCell className="py-2 text-left">
                {letra
                  ? `${letra}${index + 1}. ${grafico.nome_grafico}`
                  : grafico.nome_grafico}
              </TableCell>
              <TableCell className="py-2 text-center">
                <Input
                  name=""
                  checked={mostraGraficos}
                  type="checkbox"
                  onChange={(e) => {
                    if (e.target.checked) {
                      setGraficosId((previous) => [
                        ...previous,
                        grafico.id_grafico,
                      ]);
                    } else {
                      setGraficosId((previous) => {
                        if (graficosId.includes("all")) {
                          const arrIds = graficos.map((e: any) => e.id_grafico);
                          return arrIds.filter(
                            (id: any) => id !== grafico.id_grafico,
                          );
                        } else {
                          return previous.filter(
                            (id) => id !== grafico.id_grafico,
                          );
                        }
                      });
                    }
                  }}
                />
              </TableCell>
            </TableRow>
          );
        })}
      </tbody>
    </Table>
  );
};

export default TabelaGraficos;
