import {
  hotelTranportCreate,
  hotelTransportDelete,
  hotelTransportDetail,
  hotelTransportUpdate,
} from "@/pages/tours/lib/api";
import { TranportColumns } from "@/pages/tours/lib/column";
import type { Transport } from "@/pages/tours/lib/type";
import { Button } from "@/shared/ui/button";
import { Dialog, DialogContent } from "@/shared/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import IconSelect from "@/shared/ui/iocnSelect";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/ui/table";
import RealPagination from "@/widgets/real-pagination/ui/RealPagination";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { Loader, PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import z from "zod";

const formSchema = z.object({
  name: z.string().min(1, { message: "Majburiy maydon" }),
  name_ru: z.string().min(1, { message: "Majburiy maydon" }),
  icon_name: z.string().min(1, { message: "Majburiy maydon" }),
});

const TransportTable = ({
  data,
  page,
  pageSize,
}: {
  page: number;
  pageSize: number;
  data:
    | {
        links: { previous: string; next: string };
        total_items: number;
        total_pages: number;
        page_size: number;
        current_page: number;
        results: Transport[];
      }
    | undefined;
}) => {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [types, setTypes] = useState<"edit" | "create">("create");
  const [selectedIcon, setSelectedIcon] = useState("");
  console.log(selectedIcon);

  const queryClient = useQueryClient();

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      name_ru: "",
      icon_name: "",
    },
  });

  useEffect(() => {
    form.setValue("icon_name", selectedIcon);
  }, [selectedIcon, form]);

  const handleEdit = (id: number) => {
    setTypes("edit");
    setEditId(id);
    setOpen(true);
  };

  const { data: transportDetail, isLoading: isDetailLoading } = useQuery({
    queryKey: ["detail_transport", editId],
    queryFn: () => hotelTransportDetail({ id: editId! }),
    enabled: !!editId,
  });

  useEffect(() => {
    if (transportDetail && editId) {
      const iconName = transportDetail.data.data.icon_name || "HelpCircle";
      form.setValue("name", transportDetail.data.data.name_uz);
      form.setValue("name_ru", transportDetail.data.data.name_ru);
      form.setValue("icon_name", iconName);
      setSelectedIcon(iconName);
    }
  }, [transportDetail, editId, form, selectedIcon]);

  const { mutate: deleteMutate } = useMutation({
    mutationFn: ({ id }: { id: number }) => hotelTransportDelete({ id }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["all_transport"] });
      toast.success(t("O'chirildi"), { position: "top-center" });
    },
    onError: () =>
      toast.error(t("Xatolik yuz berdi"), { position: "top-center" }),
  });

  const { mutate: create, isPending } = useMutation({
    mutationFn: ({
      body,
    }: {
      body: { name: string; name_ru: string; icon_name: string };
    }) => hotelTranportCreate({ body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["all_transport"] });
      handleCloseDialog();
      toast.success(t("Muvaffaqiyatli qo'shildi"), { position: "top-center" });
    },
    onError: () =>
      toast.error(t("Xatolik yuz berdi"), { position: "top-center" }),
  });

  const { mutate: update, isPending: updatePending } = useMutation({
    mutationFn: ({
      body,
      id,
    }: {
      id: number;
      body: { name: string; name_ru: string; icon_name: string };
    }) => hotelTransportUpdate({ body, id }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["all_transport"] });
      handleCloseDialog();
      toast.success(t("Tahrirlandi"), { position: "top-center" });
    },
    onError: () =>
      toast.error(t("Xatolik yuz berdi"), { position: "top-center" }),
  });

  function onSubmit(values: z.infer<typeof formSchema>) {
    const body = {
      name: values.name,
      name_ru: values.name_ru,
      icon_name: selectedIcon || values.icon_name,
    };

    if (types === "create") create({ body });
    if (types === "edit" && editId) update({ id: editId, body });
  }

  const handleDelete = (id: number) => deleteMutate({ id });

  const handleCloseDialog = () => {
    setOpen(false);
    setEditId(null);
    form.reset();
  };

  const columns = TranportColumns(handleEdit, handleDelete, t);

  const table = useReactTable({
    data: data?.results ?? [],
    columns,
    getCoreRowModel: getCoreRowModel(),
    manualPagination: true,
    pageCount: data?.total_pages ?? 0,
    state: {
      pagination: {
        pageIndex: page - 1,
        pageSize: pageSize,
      },
    },
  });

  return (
    <>
      <div className="flex justify-end">
        <Button
          variant="default"
          onClick={() => {
            setTypes("create");
            setEditId(null);
            setSelectedIcon("HelpCircle");
            form.reset();
            setOpen(true);
          }}
        >
          <PlusIcon className="mr-2" />
          {t("Qo'shish")}
        </Button>
      </div>

      <div className="border border-gray-700 rounded-md overflow-hidden mt-4">
        <Table key={data?.current_page}>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id}>
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext(),
                        )}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>

          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow key={row.id}>
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext(),
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-24 text-center text-gray-400"
                >
                  {t("Ma'lumot topilmadi")}
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <RealPagination
        table={table}
        totalPages={data?.total_pages}
        namePage="pageTransport"
        namePageSize="pageTransportSize"
      />

      <Dialog
        open={open}
        onOpenChange={(isOpen) => {
          if (!isOpen) {
            handleCloseDialog();
          }
        }}
      >
        <DialogContent>
          <p className="text-xl font-semibold mb-4">
            {types === "create"
              ? t("Yangi transport qo'shish")
              : t("Tahrirlash")}
          </p>

          {isDetailLoading && types === "edit" ? (
            <div className="flex justify-center items-center h-64">
              <Loader className="animate-spin w-8 h-8" />
            </div>
          ) : (
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="space-y-6 p-2"
              >
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("Nomi (uz)")}</FormLabel>
                      <FormControl>
                        <Input placeholder={t("Nomi (uz)")} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="name_ru"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("Nomi (ru)")}</FormLabel>
                      <FormControl>
                        <Input placeholder={t("Nomi (ru)")} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="icon_name"
                  render={() => (
                    <FormItem>
                      <FormLabel>{t("Belgi (Icon)")}</FormLabel>
                      <FormControl className="w-full">
                        <IconSelect
                          setSelectedIcon={setSelectedIcon}
                          selectedIcon={selectedIcon}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="flex justify-end gap-4">
                  <Button
                    type="button"
                    onClick={handleCloseDialog}
                    className="border-slate-600 text-white hover:bg-gray-600 bg-gray-600"
                  >
                    {t("Bekor qilish")}
                  </Button>
                  <Button type="submit" disabled={isPending || updatePending}>
                    {isPending || updatePending ? (
                      <Loader className="animate-spin" />
                    ) : types === "create" ? (
                      t("Saqlash")
                    ) : (
                      t("Tahrirlash")
                    )}
                  </Button>
                </div>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
};

export default TransportTable;
