import React, { useEffect, useState } from "react";
import { Grid } from "../components/Grid/Grid";
import { useUserProfileStore } from "../context/zustand-store/userStore";
import { useApiRequest } from "../utils/useApiRequest";
import { formatJustDate, formatJustTime } from "../utils/formatTime";
import Typography from "../components/Typography/Typography";
import { EyeIcon } from "@heroicons/react/24/outline";
import { useModalStore } from "../context/zustand-store/appStore";
import { MainInfractions } from "../partials/main/MainInfractions";
import MainSubmitInspection from "../partials/main/MainSubmitInspection";
import { useDrawerStore } from "../context/zustand-store/appStore";
import Table from "../components/Table/Table";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";

const UserInspections: React.FC = () => {
  const { profile } = useUserProfileStore();
  const { openModal } = useModalStore();
  const { openDrawer } = useDrawerStore();
  const [tableData, setTableData] = useState<any[][]>([]);

  const { data: inspectionsData, refetch } = useApiRequest({
    api: `/userinspections/${profile?._id || profile?.Id}`,
    method: "get",
    queryKey: ["userinspections"],
  });

  useEffect(() => {
    if (inspectionsData) {
      const d = inspectionsData.map((field: any, i: number) => {
        return [
          i + 1,
          `${formatJustDate(field?.createdAt)} ساعت ${formatJustTime(
            field?.createdAt
          )}`,
          field.inspectors?.map((item: any, idx: number) => (
            <Typography key={idx} variant="body2" className="text-xs">
              {item.fullname}
            </Typography>
          )) || "-",
          field?.license_type,
          field?.issuer,
          field?.registration_number,
          field?.ownership_type,
          field?.unit_type,
          field?.economic_code,
          field?.document_number,
          field?.infractions?.length ? (
            <div className="flex items-center gap-2">
              <Typography variant="body2" className="text-red-600">
                دارد
              </Typography>
              <button
                onClick={() => {
                  openModal({
                    title: "مشاهده تخلفات",
                    content: (
                      <MainInfractions data={field} handleUpdate={refetch} />
                    ),
                  });
                }}
                className="p-1 text-red-600 hover:bg-red-50 rounded"
              >
                <EyeIcon className="w-5 h-5" />
              </button>
            </div>
          ) : (
            <Typography variant="body2" className="text-blue-600">
              ندارد
            </Typography>
          ),
          parseInt(field?.violation_amount || "0")?.toLocaleString() !== "NaN"
            ? parseInt(field?.violation_amount || "0")?.toLocaleString()
            : "-",
          parseInt(field?.plaintiff_damage || "0")?.toLocaleString() !== "NaN"
            ? parseInt(field?.plaintiff_damage || "0")?.toLocaleString()
            : "-",
          field?.description || "-",
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                access="submit"
                onClick={() => {
                  openDrawer({
                    title: "ویرایش بازرسی",
                    content: (
                      <MainSubmitInspection
                        item={field}
                        isEdit
                        inspectId={field?._id || field?.Id}
                        handleUpdate={refetch}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              access="submit"
              api={`inspections/${field?._id || field?.Id}`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTableData(d);
    }
  }, [inspectionsData, profile]);

  return (
    <Grid container column className="justify-center">
      <Grid container>
        <Table
          title="سوابق بازرسی من"
          columns={[
            "ردیف",
            "تاریخ بازرسی",
            "بازرسان همراه",
            "نوع پروانه کسب",
            "صادر کننده پروانه",
            "شماره ثبت",
            "نوع مالکیت",
            "نوع واحد",
            "کد اقتصادی",
            "شماره پرونده یا مجوز",
            "تخلف",
            "جمع کل تخلف",
            "جمع کل خسارت به شاکی",
            "توضیحات",
            "عملیات",
          ]}
          rows={tableData}
        />
      </Grid>
    </Grid>
  );
};

export default UserInspections;
