"use client";

import {
  addNewsCategory,
  deleteNewsCategory,
  getAllNewsCategory,
  getDetailNewsCategory,
  updateNewsCategory,
} from "@/pages/news/lib/api";
import { Button } from "@/shared/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/ui/table";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertTriangle,
  ChevronLeft,
  ChevronRight,
  Edit,
  Loader2,
  PlusCircle,
  Trash2,
} 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 NewsCategory = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;
  const newsForm = z.object({
    title: z.string().min(2, {
      message: "Username must be at least 2 characters.",
    }),
    title_ru: z.string().min(2, {
      message: "Username must be at least 2 characters.",
    }),
  });
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["news_category", currentPage],
    queryFn: () =>
      getAllNewsCategory({ page: currentPage, page_size: itemsPerPage }),
  });
  const [editItem, setEditItem] = useState<number | null>(null);

  const { data: detail } = useQuery({
    queryKey: ["news_category_detail", editItem],
    queryFn: () => getDetailNewsCategory(editItem!),
    enabled: editItem !== null,
  });

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const form = useForm<z.infer<typeof newsForm>>({
    resolver: zodResolver(newsForm),
    defaultValues: {
      title: "",
      title_ru: "",
    },
  });

  useEffect(() => {
    if (detail) {
      form.setValue("title", detail.data.data.name_uz);
      form.setValue("title_ru", detail.data.data.name_ru);
    }
  }, [editItem, form, detail]);

  const openDialog = () => {
    setIsDialogOpen(true);
  };

  const { mutate: added } = useMutation({
    mutationFn: (body: { name: string; name_ru: string }) =>
      addNewsCategory(body),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["news_category"] });
      queryClient.refetchQueries({ queryKey: ["news_category_detail"] });
      setIsDialogOpen(false);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const { mutate: edit } = useMutation({
    mutationFn: ({
      body,
      id,
    }: {
      id: number;
      body: { name: string; name_ru: string };
    }) => updateNewsCategory({ body, id }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["news_category"] });
      queryClient.refetchQueries({ queryKey: ["news_category_detail"] });
      setIsDialogOpen(false);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const { mutate: deleteCategory } = useMutation({
    mutationFn: (id: number) => deleteNewsCategory(id),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["news_category"] });
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  function onSubmit(value: z.infer<typeof newsForm>) {
    if (editItem === null) {
      added({
        name: value.title,
        name_ru: value.title_ru,
      });
    } else if (editItem !== null) {
      edit({
        id: editItem,
        body: {
          name: value.title,
          name_ru: value.title_ru,
        },
      });
    }
  }

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

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 text-white gap-4 w-full">
        <Loader2 className="w-10 h-10 animate-spin text-cyan-400" />
        <p className="text-slate-400">{t("Ma'lumotlar yuklanmoqda...")}</p>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 w-full text-center text-white gap-4">
        <AlertTriangle className="w-10 h-10 text-red-500" />
        <p className="text-lg">
          {t("Ma'lumotlarni yuklashda xatolik yuz berdi.")}
        </p>
        <Button
          onClick={() => refetch()}
          className="bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-lg px-5 py-2 hover:opacity-90"
        >
          {t("Qayta urinish")}
        </Button>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-900 w-full text-gray-100 p-8">
      <div className="flex items-center justify-between mb-8">
        <h1 className="text-3xl font-semibold tracking-tight">
          {t("News Categories")}
        </h1>

        <Button
          onClick={() => {
            openDialog();
            form.reset();
            setEditItem(null);
          }}
          className="flex items-center bg-blue-600 hover:bg-blue-700 text-white"
        >
          <PlusCircle className="w-4 h-4 mr-2" /> {t("Yangi qo‘shish")}
        </Button>
      </div>
      <div className="rounded-lg border border-gray-800 overflow-hidden bg-gray-900">
        <Table>
          <TableHeader className="bg-gray-800/50">
            <TableRow>
              <TableHead className="text-gray-300 w-[60px]">#</TableHead>
              <TableHead className="text-gray-300">
                {t("Kategoriya nomi")}
              </TableHead>
              {/* <TableHead className="text-gray-300 text-center">
                {t("Yangiliklar soni")}
              </TableHead> */}
              <TableHead className="text-gray-300 text-right">
                {t("Harakatlar")}
              </TableHead>
            </TableRow>
          </TableHeader>

          <TableBody>
            {data && data?.data.data.total_items > 0 ? (
              data?.data.data.results.map((cat, index) => (
                <TableRow
                  key={cat.id}
                  className="border-b border-gray-800 hover:bg-gray-800/40 transition-colors"
                >
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <div>
                        <p className="font-medium">{cat.name}</p>
                      </div>
                    </div>
                  </TableCell>

                  {/* <TableCell className="text-center">
                    <Badge variant="secondary" className="bg-gray-700">
                      {cat.}
                    </Badge>
                  </TableCell> */}

                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        className="border-gray-700 text-gray-200 hover:bg-gray-800"
                        onClick={() => {
                          openDialog();
                          setEditItem(cat.id);
                        }}
                      >
                        <Edit className="w-4 h-4 mr-1" /> {t("Tahrirlash")}
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        onClick={() => handleDelete(cat.id)}
                      >
                        <Trash2 className="w-4 h-4 mr-1" /> {t("O'chirish")}
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={4}
                  className="text-center py-8 text-gray-400"
                >
                  {t("Hech qanday kategoriya topilmadi")}
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      <Dialog
        open={isDialogOpen}
        onOpenChange={(open) => {
          setIsDialogOpen(open);
          setEditItem(null);
        }}
      >
        <DialogContent className="bg-gray-900 border border-gray-700 text-gray-100">
          <DialogHeader>
            <DialogTitle>
              {editItem
                ? t("Kategoriya tahrirlash")
                : t("Yangi kategoriya qo‘shish")}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="space-y-6 bg-gray-900"
              >
                <FormField
                  control={form.control}
                  name="title"
                  render={({ field }) => (
                    <FormItem>
                      <Label className="text-md">{t("Kategoriya nomi")}</Label>
                      <FormControl>
                        <Input
                          placeholder={t("Kategoriya nomi")}
                          {...field}
                          className="h-12 !text-md bg-gray-800 border-gray-700 text-white"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="title_ru"
                  render={({ field }) => (
                    <FormItem>
                      <Label className="text-md">
                        {t("Kategoriya nomi")} (ru)
                      </Label>
                      <FormControl>
                        <Input
                          placeholder={t("Kategoriya nomi")}
                          {...field}
                          className="h-12 !text-md bg-gray-800 border-gray-700 text-white"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className="flex justify-end">
                  <Button
                    type="submit"
                    className="bg-blue-600 px-5 py-5 hover:bg-blue-700 text-white mt-4 cursor-pointer"
                  >
                    {t("Saqlash")}
                  </Button>
                </div>
              </form>
            </Form>
          </div>
        </DialogContent>
      </Dialog>
      <div className="flex justify-end gap-2 mt-10">
        <button
          disabled={currentPage === 1}
          onClick={() => setCurrentPage((p) => Math.max(p - 1, 1))}
          className="p-2 rounded-lg border border-slate-600 text-slate-300 hover:bg-slate-700/50 disabled:opacity-50 disabled:cursor-not-allowed transition-all hover:border-slate-500"
        >
          <ChevronLeft className="w-5 h-5" />
        </button>

        {[...Array(data?.data.data.total_pages)].map((_, i) => (
          <button
            key={i}
            onClick={() => setCurrentPage(i + 1)}
            className={`px-4 py-2 rounded-lg border transition-all font-medium ${
              currentPage === i + 1
                ? "bg-gradient-to-r from-blue-600 to-cyan-600 border-blue-500 text-white shadow-lg shadow-cyan-500/50"
                : "border-slate-600 text-slate-300 hover:bg-slate-700/50 hover:border-slate-500"
            }`}
          >
            {i + 1}
          </button>
        ))}

        <button
          disabled={currentPage === data?.data.data.total_pages}
          onClick={() =>
            setCurrentPage((p) =>
              Math.min(p + 1, data ? data?.data.data.total_pages : 0),
            )
          }
          className="p-2 rounded-lg border border-slate-600 text-slate-300 hover:bg-slate-700/50 disabled:opacity-50 disabled:cursor-not-allowed transition-all hover:border-slate-500"
        >
          <ChevronRight className="w-5 h-5" />
        </button>
      </div>
    </div>
  );
};

export default NewsCategory;
