"use client";

import { getDetailAgency, updateAgencyStatus } from "@/pages/agencies/lib/api";
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
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 { Loader2 } from "lucide-react";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import { z } from "zod";

const formSchema = z.object({
  status: z.enum(["pending", "approved", "cancelled"]),
  share_percentage: z
    .number({ message: "Share percentage raqam bo‘lishi kerak" })
    .min(0)
    .max(100),
  name: z.string().min(1, "Nom kiritish shart"),
  addres: z.string().min(1, "Manzil kiritish shart"),
  email: z.string().email("Email noto‘g‘ri"),
  phone: z.string().min(3, "Telefon raqami noto‘g‘ri"),
  web_site: z.string().url("URL noto‘g‘ri"),
});

type FormData = z.infer<typeof formSchema>;

const EditAgency = () => {
  const params = useParams();
  const { t } = useTranslation();
  const router = useNavigate();
  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      status: "pending",
      share_percentage: 0,
      name: "",
      addres: "",
      email: "",
      phone: "+998",
      web_site: "",
    },
  });
  const queryClient = useQueryClient();

  const { data, isPending } = useQuery({
    queryKey: ["detail_agency", params.id],
    queryFn: () => getDetailAgency({ id: Number(params.id) }),
  });

  const { mutate } = useMutation({
    mutationFn: (body: {
      status: "pending" | "approved" | "cancelled";
      custom_id?: string;
      share_percentage?: number;
      name?: string;
      addres?: string;
      email?: string;
      phone?: string;
      web_site?: string;
      ticket_sold_count?: number;
      total_income?: number;
    }) =>
      updateAgencyStatus({
        id: Number(params.id),
        body,
      }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["detail_agency"] });
      queryClient.refetchQueries({ queryKey: ["all_agency"] });
      router(-1);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  useEffect(() => {
    if (data?.data?.data) {
      const agency = data.data.data;
      form.setValue("status", agency.status);
      form.setValue("share_percentage", agency.share_percentage);
      form.setValue("name", agency.name);
      form.setValue("addres", agency.addres);
      form.setValue("email", agency.email);
      form.setValue("phone", agency.phone);
      form.setValue("web_site", agency.web_site);
    }
  }, [data, form]);

  const onSubmit = (values: FormData) => {
    mutate({
      status: values.status,
      share_percentage: values.share_percentage,
      name: values.name,
      addres: values.addres,
      email: values.email,
      phone: values.phone,
      web_site: values.web_site,
    });
  };

  return (
    <Card className="w-[80%] mx-auto mt-10 bg-gray-900">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">
          {t("Tahrirlash")}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6"
            noValidate
          >
            <FormField
              control={form.control}
              name="share_percentage"
              render={({ field }) => (
                <FormItem>
                  <FormLabel> {t("Komissiya")}</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      min={0}
                      max={100}
                      {...field}
                      onChange={(e) => field.onChange(Number(e.target.value))}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("Nomi")}</FormLabel>
                  <FormControl>
                    <Input placeholder={t("Nomi")} {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="addres"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("Manzil")}</FormLabel>
                  <FormControl>
                    <Input placeholder={t("Manzil")} {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("Email")}</FormLabel>
                  <FormControl>
                    <Input
                      type="email"
                      placeholder="user@example.com"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("Telefon raqam")}</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="+998 90 123-45-67"
                      value={formatPhone(field.value)}
                      onChange={field.onChange}
                      onBlur={field.onBlur}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="web_site"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("Veb-sayt")}</FormLabel>
                  <FormControl>
                    <Input placeholder="https://example.com" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("Status")}</FormLabel>
                  <Select
                    value={field.value}
                    key={field.value}
                    onValueChange={field.onChange}
                  >
                    <FormControl>
                      <SelectTrigger className="w-full">
                        <SelectValue placeholder="Select status" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="pending">{t("Kutilmoqda")}</SelectItem>
                      <SelectItem value="approved"> {t("Faol")}</SelectItem>
                      <SelectItem value="cancelled">
                        {t("Cancelled")}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button type="submit" className="w-full cursor-pointer">
              {isPending ? <Loader2 className="animate-spin" /> : t("Saqlash")}
            </Button>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
};

export default EditAgency;
