"use client";

import { getAllNewsCategory } from "@/pages/news/lib/api";
import { useNewsStore } from "@/pages/news/lib/data";
import { newsForm } from "@/pages/news/lib/form";
import { Button } from "@/shared/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/shared/ui/form";
import { InfiniteScrollSelect } from "@/shared/ui/infiniteScrollSelect";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import { Textarea } from "@/shared/ui/textarea";
import { zodResolver } from "@hookform/resolvers/zod";
import { useInfiniteQuery } from "@tanstack/react-query";
import { XIcon } from "lucide-react";
import { useEffect, useRef, type Dispatch, type SetStateAction } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import type z from "zod";

interface Data {
  id: number;
  title: string;
  title_ru: string;
  title_uz: string;
  image: string;
  text: string;
  text_ru: string;
  text_uz: string;
  is_public: boolean;
  category: {
    id: number;
    name: string;
    name_ru: string;
    name_uz: string;
  };
  post_tags: [
    {
      id: number;
      name: string;
      name_ru: string;
      name_uz: string;
    },
  ];
  post_images: [
    {
      image: string;
      text: string;
      text_ru: string;
      text_uz: string;
    },
  ];
}

const StepOne = ({
  setStep,
  data: detail,
}: {
  setStep: Dispatch<SetStateAction<number>>;
  isEditMode: boolean;
  data: Data;
  id: number;
}) => {
  const { t } = useTranslation();
  const { setStepOneData, stepOneData } = useNewsStore();
  const hasReset = useRef(false);

  // News Category fetch - barcha kategoriyalarni bir martada
  const {
    data: categoryData,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading: isCategoriesLoading,
  } = useInfiniteQuery({
    queryKey: ["news_category"],
    queryFn: ({ pageParam = 1 }) =>
      getAllNewsCategory({ page: pageParam, page_size: 100 }),
    getNextPageParam: (lastPage) => {
      const currentPage = lastPage.data.data.current_page;
      const totalPages = lastPage.data.data.total_pages;
      return currentPage < totalPages ? currentPage + 1 : undefined;
    },
    initialPageParam: 1,
  });

  // Avtomatik barcha sahifalarni yuklash
  useEffect(() => {
    if (hasNextPage && !isFetchingNextPage) {
      fetchNextPage();
    }
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);

  const allCategories =
    categoryData?.pages.flatMap((page) => page.data.data.results) ?? [];

  // Form setup
  const form = useForm<z.infer<typeof newsForm>>({
    resolver: zodResolver(newsForm),
    defaultValues: {
      title: stepOneData.title || "",
      category: stepOneData.category || undefined,
      banner: stepOneData.banner,
      desc: stepOneData.desc || "",
      desc_ru: stepOneData.desc_ru || "",
      title_ru: stepOneData.title_ru || "",
    },
  });

  // Reset form when detail & categories are ready (EDIT MODE)
  useEffect(() => {
    if (
      !detail ||
      allCategories.length === 0 ||
      hasReset.current ||
      isCategoriesLoading
    ) {
      return;
    }

    const categoryId = detail.category.id;

    form.reset({
      banner: detail.image as any,
      category: categoryId,
      title: detail.title_uz,
      title_ru: detail.title_ru,
      desc: detail.text_uz,
      desc_ru: detail.text_ru,
    });

    // Kategoriyani alohida set qilish
    setTimeout(() => {
      form.setValue("category", categoryId, { shouldValidate: false });
    }, 0);

    hasReset.current = true;
  }, [detail, allCategories, form, isCategoriesLoading]);

  function onSubmit(values: z.infer<typeof newsForm>) {
    setStepOneData(values);
    setStep(2);
  }

  const banner = form.watch("banner");
  const bannerSrc =
    banner instanceof File ? URL.createObjectURL(banner) : String(banner);

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="space-y-6 bg-gray-900"
      >
        {/* Title */}
        <FormField
          control={form.control}
          name="title"
          render={({ field }) => (
            <FormItem>
              <Label className="text-md">{t("Yangilik nomi")}</Label>
              <FormControl>
                <Input
                  placeholder={t("Yangilik nomi")}
                  {...field}
                  className="h-12 !text-md bg-gray-800 border-gray-700 text-white"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Title RU */}
        <FormField
          control={form.control}
          name="title_ru"
          render={({ field }) => (
            <FormItem>
              <Label className="text-md">{t("Yangilik nomi")} (ru)</Label>
              <FormControl>
                <Input
                  placeholder={t("Yangilik nomi") + " (ru)"}
                  {...field}
                  className="h-12 !text-md bg-gray-800 border-gray-700 text-white"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Description */}
        <FormField
          control={form.control}
          name="desc"
          render={({ field }) => (
            <FormItem>
              <Label className="text-md">{t("Yangilik haqida")}</Label>
              <FormControl>
                <Textarea
                  placeholder={t("Yangilik haqida")}
                  {...field}
                  className="min-h-48 max-h-56 !text-md bg-gray-800 border-gray-700 text-white"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Description RU */}
        <FormField
          control={form.control}
          name="desc_ru"
          render={({ field }) => (
            <FormItem>
              <Label className="text-md">{t("Yangilik haqida")} (ru)</Label>
              <FormControl>
                <Textarea
                  placeholder={t("Yangilik haqida") + " (ru)"}
                  {...field}
                  className="min-h-48 max-h-56 !text-md bg-gray-800 border-gray-700 text-white"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Category */}
        <FormField
          control={form.control}
          name="category"
          render={({ field }) => {
            console.log("Category field value:", field.value);
            console.log("All categories:", allCategories);

            return (
              <FormItem>
                <Label className="text-md">{t("Kategoriya")}</Label>
                <FormControl>
                  <InfiniteScrollSelect
                    value={field.value ? String(field.value) : ""}
                    onValueChange={(value) => {
                      const numValue = Number(value);
                      field.onChange(numValue);
                    }}
                    placeholder={t("Kategoriya tanlang")}
                    label={t("Kategoriyalar")}
                    data={allCategories}
                    hasNextPage={hasNextPage}
                    isFetchingNextPage={isFetchingNextPage}
                    fetchNextPage={fetchNextPage}
                    renderOption={(cat) => ({
                      key: cat.id,
                      value: String(cat.id),
                      label: cat.name,
                    })}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            );
          }}
        />

        {/* Banner */}
        <FormField
          control={form.control}
          name="banner"
          render={() => (
            <FormItem>
              <Label className="text-md">{t("Banner rasmi")}</Label>
              <FormControl>
                <div className="flex flex-col gap-3 w-full">
                  <Input
                    type="file"
                    id="banner-file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) {
                        form.setValue("banner", file, { shouldValidate: true });
                      }
                    }}
                    className="hidden"
                  />

                  <label
                    htmlFor="banner-file"
                    className="w-full border-2 border-dashed h-40 border-gray-500 flex flex-col items-center gap-2 justify-center py-4 rounded-2xl cursor-pointer hover:bg-gray-800 transition"
                  >
                    <p className="font-semibold text-xl text-white">
                      {t("Drag or select files")}
                    </p>
                    <p className="text-gray-400 text-sm">
                      {t("Drop files here or click to browse")}
                    </p>
                  </label>

                  {form.watch("banner") && (
                    <div className="relative w-32 h-32 rounded-md overflow-hidden border border-gray-600">
                      <img
                        src={bannerSrc}
                        alt="Banner preview"
                        className="object-cover w-full h-full"
                      />
                      <button
                        type="button"
                        onClick={() =>
                          form.setValue("banner", null as any, {
                            shouldValidate: true,
                          })
                        }
                        className="absolute top-1 right-1 bg-black/70 rounded-full p-1 hover:bg-black/90"
                      >
                        <XIcon className="size-4 text-red-400" />
                      </button>
                    </div>
                  )}
                </div>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Submit */}
        <div className="w-full 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("Keyingisi")}
          </Button>
        </div>
      </form>
    </Form>
  );
};

export default StepOne;
