import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import { Grid } from "../../components/Grid/Grid";
import Table from "../../components/Table/Table";
import Button from "../../components/Button/Button";
import { useModalStore } from "../../context/zustand-store/appStore";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { TagDetails } from "../../partials/tagging/TagDetails";
import { useParams } from "@tanstack/react-router";
import { TableButton } from "../../components/TableButton/TableButton";
import AutoComplete from "../../components/AutoComplete/AutoComplete";

const speciesMap: Record<number, string> = {
  1: "گاو",
  2: "گاومیش",
  3: "شتر",
  4: "گوسفند",
  5: "بز",
};

const statusOptions = [
  { key: "F", value: "آزاد" },
  { key: "A", value: "پلاک شده" },
  { key: "R", value: "رزرو" },
];

export default function Tags() {
  const { openModal } = useModalStore();
  const [tableInfo, setTableInfo] = useState({ page: 1, page_size: 10 });
  const [tagsTableData, setTagsTableData] = useState([]);
  const { id, from, to } = useParams({ strict: false });
  const [selectedStatus, setSelectedStatus] = useState<(string | number)[]>([]);

  const { data: tagsData, refetch } = useApiRequest({
    api: `/tag/web/api/v1/tag/${id ? id + "/tags_by_batch" : ""}`,
    method: "get",
    queryKey: ["tagsList", tableInfo, selectedStatus],
    params: {
      ...tableInfo,
      status: selectedStatus.length ? selectedStatus[0] : undefined,
    },
  });

  const { data: tagDashboardData } = useApiRequest({
    api: id
      ? `/tag/web/api/v1/tag_batch/${id}/inner_dashboard`
      : "/tag/web/api/v1/tag/tag_dashboard/",
    method: "get",
    queryKey: ["tagDashboard"],
  });

  useEffect(() => {
    if (tagsData?.results) {
      const formattedData = tagsData.results.map((item: any, index: number) => {
        return [
          tableInfo.page === 1
            ? index + 1
            : index + tableInfo.page_size * (tableInfo.page - 1) + 1,
          item?.tag_code || "-",
          item?.organization?.name || "بدون سازمان",
          item?.species_code === 1
            ? "گاو"
            : item?.species_code === 2
              ? "گاومیش"
              : item?.species_code === 3
                ? "شتر"
                : item?.species_code === 4
                  ? "گوسفند"
                  : item?.species_code === 5
                    ? "بز"
                    : "نامشخص",
          item?.status === "F"
            ? "آزاد"
            : item?.status === "A"
              ? "پلاک شده"
              : item?.status === "R"
                ? "رزرو"
                : "-",
          item?.ownership_code || "-",
          <Popover key={item.id}>
            <Tooltip title="جزئیات پلاک" position="right">
              <Button
                variant="detail"
                page="tagging"
                access="Tag-Details"
                disabled={item?.status === "F"}
                onClick={() => {
                  openModal({
                    title: "جزئیات پلاک",
                    content: <TagDetails tagId={item.id} />,
                    isFullSize: true,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="tagging"
              access="Delete-Tag"
              api={`/tag/web/api/v1/tag/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTagsTableData(formattedData);
    }
  }, [tagsData]);

  return (
    <Grid container column className="gap-4 mt-2">
      {tagDashboardData && (
        <Grid isDashboard>
          <Table
            isDashboard
            title="خلاصه اطلاعات"
            noPagination
            noSearch
            columns={
              id
                ? [
                    "تعداد پلاک",
                    "پلاک های توزیع شده",
                    "تعداد پلاک های گروه پلاک",
                    "تعداد پلاک های توزیع شده",
                    "تعداد پلاک های باقیمانده",
                    "آمار گونه ای",
                  ]
                : [
                    "تعداد کل",
                    "تعداد پلاک های آزاد",
                    "تعداد پلاک شده",
                    "گاو",
                    "گاومیش",
                    "شتر",
                    "گوسفند",
                    "بز",
                  ]
            }
            rows={
              id
                ? [
                    [
                      tagDashboardData?.batch_count?.toLocaleString() || 0,
                      tagDashboardData?.has_distributed_batches_number?.toLocaleString() ||
                        0,
                      tagDashboardData?.tag_count_created_by_batch?.toLocaleString() ||
                        0,
                      tagDashboardData?.total_distributed_tags?.toLocaleString() ||
                        0,
                      tagDashboardData?.total_remaining_tags?.toLocaleString() ||
                        0,
                      <TableButton
                        key="species-stats"
                        size="small"
                        onClick={() =>
                          openModal({
                            title: "آمار گونه‌ای",
                            isFullSize: true,
                            content: (
                              <BatchBySpeciesModal
                                batchData={
                                  tagDashboardData?.batch_data_by_species || []
                                }
                                onRowAction={(row) => {
                                  openModal({
                                    title: `جزئیات ${
                                      speciesMap[row?.species_code] ?? "-"
                                    }`,
                                    content: (
                                      <div className="space-y-3">
                                        <div className="flex items-center justify-between text-sm">
                                          <span className="text-gray-600 dark:text-gray-300">
                                            تعداد بچ
                                          </span>
                                          <span className="font-semibold text-gray-900 dark:text-gray-100">
                                            {row?.batch_count?.toLocaleString?.() ??
                                              0}
                                          </span>
                                        </div>
                                        <div className="flex items-center justify-between text-sm">
                                          <span className="text-gray-600 dark:text-gray-300">
                                            پلاک تولید شده
                                          </span>
                                          <span className="font-semibold text-gray-900 dark:text-gray-100">
                                            {row?.tag_count_created_by_batch?.toLocaleString?.() ??
                                              0}
                                          </span>
                                        </div>
                                        <div className="flex items-center justify-between text-sm">
                                          <span className="text-gray-600 dark:text-gray-300">
                                            پلاک توزیع شده
                                          </span>
                                          <span className="font-semibold text-gray-900 dark:text-gray-100">
                                            {row?.total_distributed_tags?.toLocaleString?.() ??
                                              0}
                                          </span>
                                        </div>
                                        <div className="flex items-center justify-between text-sm">
                                          <span className="text-gray-600 dark:text-gray-300">
                                            پلاک باقی‌مانده
                                          </span>
                                          <span className="font-semibold text-gray-900 dark:text-gray-100">
                                            {row?.total_remaining_tags?.toLocaleString?.() ??
                                              0}
                                          </span>
                                        </div>
                                        <div className="flex items-center justify-between text-sm">
                                          <span className="text-gray-600 dark:text-gray-300">
                                            بچ‌های توزیع‌شده
                                          </span>
                                          <span className="font-semibold text-gray-900 dark:text-gray-100">
                                            {row?.has_distributed_batches_number?.toLocaleString?.() ??
                                              0}
                                          </span>
                                        </div>
                                      </div>
                                    ),
                                  });
                                }}
                              />
                            ),
                          })
                        }
                      >
                        مشاهده
                      </TableButton>,
                    ],
                  ]
                : [
                    [
                      tagDashboardData?.count?.toLocaleString() || 0,
                      tagDashboardData?.free_count?.toLocaleString() || 0,
                      tagDashboardData?.assign_count?.toLocaleString() || 0,
                      tagDashboardData?.cow_count?.toLocaleString() || 0,
                      tagDashboardData?.buffalo_count?.toLocaleString() || 0,
                      tagDashboardData?.camel_count?.toLocaleString() || 0,
                      tagDashboardData?.sheep_count?.toLocaleString() || 0,
                      tagDashboardData?.goat_count?.toLocaleString() || 0,
                    ],
                  ]
            }
          />
        </Grid>
      )}

      <Grid container className="items-center gap-2">
        <Grid>
          <AutoComplete
            data={statusOptions}
            selectedKeys={selectedStatus}
            onChange={setSelectedStatus}
            title="فیلتر پلاک ها"
          />
        </Grid>
      </Grid>

      <Table
        className="mt-2"
        onChange={setTableInfo}
        count={tagsData?.count || 0}
        isPaginated
        title={!id ? "لیست پلاک" : "لیست پلاک های بازه " + from + " تا " + to}
        columns={[
          "ردیف",
          "پلاک",
          "سازمان ثبت کننده",
          "کد گونه",
          "وضعیت",
          "کد مالکیت ثبتی",
          "عملیات",
        ]}
        rows={tagsTableData}
      />
    </Grid>
  );
}

function BatchBySpeciesModal({
  batchData = [],
}: {
  batchData: Array<any>;
  onRowAction?: (row: any, index: number) => void;
}) {
  return (
    <div className="w-full">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {batchData?.map((row, idx) => {
          const speciesName = speciesMap[row?.species_code] ?? "-";
          return (
            <div
              key={idx}
              className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm p-4 flex flex-col"
            >
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-primary/70"></div>
                  <span className="text-sm font-bold text-gray-900 dark:text-gray-100">
                    {speciesName}
                  </span>
                </div>
              </div>
              <div className="space-y-2">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-300">
                    تعداد گروه پلاک
                  </span>
                  <span className="font-semibold text-gray-900 dark:text-gray-100">
                    {row?.batch_count?.toLocaleString?.() ?? 0}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-300">
                    گروه پلاک های توزیع‌شده
                  </span>
                  <span className="font-semibold text-gray-900 dark:text-gray-100">
                    {row?.has_distributed_batches_number?.toLocaleString?.() ??
                      0}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-300">
                    پلاک تولید شده
                  </span>
                  <span className="font-semibold text-gray-900 dark:text-gray-100">
                    {row?.tag_count_created_by_batch?.toLocaleString?.() ?? 0}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-300">
                    پلاک توزیع شده
                  </span>
                  <span className="font-semibold text-gray-900 dark:text-gray-100">
                    {row?.total_distributed_tags?.toLocaleString?.() ?? 0}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-300">
                    پلاک باقی‌مانده
                  </span>
                  <span className="font-semibold text-gray-900 dark:text-gray-100">
                    {row?.total_remaining_tags?.toLocaleString?.() ?? 0}
                  </span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
