import {
  createEmployees,
  editEmployees,
  getDetailEmployees,
} from "@/pages/employees/lib/api";
import formatPhone from "@/shared/lib/formatPhone";
import onlyNumber from "@/shared/lib/onlyNumber";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/ui/select";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Loader, X } from "lucide-react";
import { useEffect, type Dispatch, type SetStateAction } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import z from "zod";

const roles = ["buxgalter", "operator"] as const;

// ✅ Conditional schema - create uchun password majburiy, edit uchun yo'q
const createEmployeeSchema = z.object({
  firstname: z.string().min(2, "Kamida 2 ta belgidan iborat bo'lishi kerak"),
  lastname: z.string().min(2, "Kamida 2 ta belgidan iborat bo'lishi kerak"),
  phone: z.string().min(9, "Telefon raqam noto'g'ri"),
  role: z.string().min(1, { message: "Majburiy maydon" }),
  password: z
    .string()
    .min(6, "Parol kamida 6 ta belgidan iborat bo'lishi kerak"),
});

const editEmployeeSchema = z.object({
  firstname: z.string().min(2, "Kamida 2 ta belgidan iborat bo'lishi kerak"),
  lastname: z.string().min(2, "Kamida 2 ta belgidan iborat bo'lishi kerak"),
  phone: z.string().min(9, "Telefon raqam noto'g'ri"),
  role: z.string().min(1, { message: "Majburiy maydon" }),
});

type CreateEmployeeFormValues = z.infer<typeof createEmployeeSchema>;
type EditEmployeeFormValues = z.infer<typeof editEmployeeSchema>;
type EmployeeFormValues = CreateEmployeeFormValues | EditEmployeeFormValues;

const EditEmployees = ({
  modalMode,
  editId,
  showModal,
  setEditId,
  setShowModal,
}: {
  modalMode: "add" | "edit";
  showModal: boolean;
  setEditId: Dispatch<SetStateAction<number | null>>;
  editId: number | null;
  setShowModal: Dispatch<SetStateAction<boolean>>;
}) => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  // ✅ Dinamik schema - modalMode'ga qarab
  const form = useForm<EmployeeFormValues>({
    resolver: zodResolver(
      modalMode === "add" ? createEmployeeSchema : editEmployeeSchema,
    ),
    defaultValues: {
      firstname: "",
      lastname: "",
      phone: "+998",
      role: "",
      ...(modalMode === "add" && { password: "" }),
    },
  });

  const { data } = useQuery({
    queryKey: ["detail_employees", editId],
    queryFn: () => getDetailEmployees({ id: editId! }),
    select(data) {
      return data.data.data;
    },
    enabled: !!editId,
  });

  useEffect(() => {
    if (data && editId) {
      form.reset({
        firstname: data.first_name,
        lastname: data.last_name,
        phone: data.phone,
        role: data.role,
      });
    } else if (!editId && showModal) {
      form.reset({
        firstname: "",
        lastname: "",
        phone: "+998",
        role: "",
        ...(modalMode === "add" && { password: "" }),
      });
    }
  }, [data, editId, showModal, modalMode, form]);

  const { mutate: create, isPending } = useMutation({
    mutationFn: ({
      body,
    }: {
      body: {
        first_name: string;
        last_name: string;
        phone: string;
        email: string | null;
        role: "buxgalter" | "operator";
        password: string;
      };
    }) => createEmployees({ body }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["detail_employees"] });
      queryClient.refetchQueries({ queryKey: ["employees"] });
      setShowModal(false);
      setEditId(null);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const { mutate: edit, isPending: editPengding } = useMutation({
    mutationFn: ({
      body,
      id,
    }: {
      id: number;
      body: {
        first_name: string;
        last_name: string;
        phone: string;
        email: string | null;
        role: "buxgalter" | "operator";
      };
    }) => editEmployees({ id, body }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["detail_employees"] });
      queryClient.refetchQueries({ queryKey: ["employees"] });
      setShowModal(false);
      setEditId(null);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  function onSubmit(values: EmployeeFormValues) {
    if (modalMode === "add" && editId === null) {
      create({
        body: {
          email: null,
          first_name: values.firstname,
          last_name: values.lastname,
          phone: onlyNumber(values.phone),
          role: values.role as "buxgalter" | "operator",
          password: (values as CreateEmployeeFormValues).password,
        },
      });
    } else if (modalMode === "edit" && editId !== null) {
      edit({
        id: editId,
        body: {
          email: null,
          first_name: values.firstname,
          last_name: values.lastname,
          phone: onlyNumber(values.phone),
          role: values.role as "buxgalter" | "operator",
        },
      });
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
      <div className="bg-gray-800 rounded-2xl p-8 max-w-md w-full border border-gray-700 shadow-2xl">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-white">
            {modalMode === "add"
              ? t("Xodim qo'shish")
              : t("Xodimni tahrirlash")}
          </h2>
          <button
            onClick={() => {
              setShowModal(false);
              setEditId(null);
              form.reset();
            }}
            className="text-gray-400 hover:text-white transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="firstname"
              render={({ field }) => (
                <FormItem>
                  <Label>{t("Ismi")}</Label>
                  <FormControl>
                    <Input placeholder="Ismi" {...field} className="h-12" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="lastname"
              render={({ field }) => (
                <FormItem>
                  <Label>{t("Familiyasi")}</Label>
                  <FormControl>
                    <Input
                      placeholder="Familiyasi"
                      {...field}
                      className="h-12"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <Label>{t("Telefon raqami")}</Label>
                  <FormControl>
                    <Input
                      placeholder="+998 90 123 45 67"
                      {...field}
                      value={formatPhone(field.value)}
                      className="h-12"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* ✅ Password field - faqat "add" modeda ko'rinadi */}
            {modalMode === "add" && (
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <Label>{t("Parol")}</Label>
                    <FormControl>
                      <Input
                        type="password"
                        placeholder="••••••"
                        {...field}
                        className="h-12"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            <FormField
              control={form.control}
              name="role"
              render={({ field }) => (
                <FormItem>
                  <Label>{t("Role")}</Label>
                  <Select
                    key={field.value}
                    value={field.value}
                    onValueChange={(val) => field.onChange(val)}
                  >
                    <SelectTrigger className="w-full !h-12 cursor-pointer">
                      <SelectValue placeholder={t("Role tanlang")} />
                    </SelectTrigger>
                    <SelectContent>
                      {roles.map((r) => (
                        <SelectItem key={r} value={r}>
                          {t(r)}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="flex gap-3 pt-4">
              <button
                type="submit"
                className="flex-1 cursor-pointer bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg font-semibold transition-all shadow-lg"
              >
                {isPending || editPengding ? (
                  <Loader className="animate-spin" />
                ) : modalMode === "add" ? (
                  t("Qo'shish")
                ) : (
                  t("Saqlash")
                )}
              </button>
              <button
                type="button"
                onClick={() => {
                  setEditId(null);
                  setShowModal(false);
                  form.reset();
                }}
                className="flex-1 bg-gray-700 cursor-pointer hover:bg-gray-600 text-white px-6 py-3 rounded-lg font-semibold transition-all"
              >
                {t("Bekor qilish")}
              </button>
            </div>
          </form>
        </Form>
      </div>
    </div>
  );
};

export default EditEmployees;
