import { getRegions } from "@/shared/api/regionSvc";
import { createUserOrder } from "@/shared/api/userOrdersSvc";
import formatPhone from "@/shared/lib/formatPhone";
import { Product } from "@/shared/types/product";
import { Button } from "@/shared/ui/button";
import { DialogFooter } from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import { RadioGroup, RadioGroupItem } from "@/shared/ui/radio-group";
import { TabsContent } from "@/shared/ui/tabs";
import { useQuery } from "@tanstack/react-query";
import { Form, Formik } from "formik";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import React, { useState } from "react";
import { toast } from "sonner";

interface Props {
  product: Product;
  setIsDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
}

const LegalTab = ({ product, setIsDialogOpen }: Props) => {
  const t = useTranslations("")
  const { data: regions } = useQuery({
    queryKey: ["getRegions"],
    queryFn: getRegions,
  });

  const [isOrderCreating, setIsOrderCreating] = useState(false);
  const [corpDistricts, setCorpDistricts] = useState<
    { id: number; name: string }[] | null
  >(null);

  const handleCorpRegionChange = (regionId: number) => {
    const selectedRegion = regions?.data?.find(
      (region) => region.id === regionId
    );
    setCorpDistricts(selectedRegion?.cities || []);
  };

  return (
    <Formik
      initialValues={{
        phone: "+998 ",
        director_full_name: "",
        company_name: "",
        inn: "",
        bank_name: "",
        mfo: "",
        oked: "",
        payment_account: "",
        address: "",
        home: "",
        landmark: "",
        city_id: "",
        branch_id: 1,
        with_installation: true,
        delivery_type: "delivery",
        payment_type: "bank",
        with_didox: true,
        products: [{ id: product.id, count: 1 }],
      }}
      onSubmit={async (values, helpers) => {
        setIsOrderCreating(true);
        let payload = {
          branch_id: 1,
          type: "ready_solutions",
          delivery_type: values.delivery_type,
          client_type: "legal",
          client_information: {
            director_full_name: values.director_full_name,
            company_name: values.company_name,
            inn: values.inn,
            bank_name: values.bank_name,
            mfo: values.mfo,
            oked: values.oked,
            payment_account: values.payment_account,
            address: values.address,
            email: "",
            phone: Number(values.phone.replace(/\D/g, "")),
          },
          address: {
            city_id: Number(values.city_id),
            address: values.address,
            home: values.home,
            landmark: values.landmark,
          },
          with_installation: values.with_installation,
          payment_type: values.payment_type,
          with_didox: values.with_didox,
          products: values.products,
        };

        try {
          await createUserOrder(payload);
          toast.success(t("Buyurtma muvaffaqiyatli yaratildi!"), {
            description: t("Siz bilan tez orada bog'lanamiz"),
          });
          setIsDialogOpen(false);
          setIsOrderCreating(false);
        } catch (e: any) {
          toast.error(t("Buyurtma yaratishda xatolik!"), {
            description:
              t("Ma'lumotlar to'liq kiritilganligiga ishonch hosil qiling yoki qaytadan urinib ko'ring"),
          });
          setIsOrderCreating(false);
        }
      }}
    >
      {(formikProps) => (
        <Form>
          {/* Legal */}
          <TabsContent value="legal" className="space-y-4 mt-4">
            <div className="grid grid-cols-2 gap-4">
              <Input
                placeholder={t("Kompaniya nomi")}
                onChange={formikProps.handleChange("company_name")}
              />
              <Input
                placeholder={t("Direktor")}
                onChange={formikProps.handleChange("director_full_name")}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <Input
                placeholder={t("Yuridik manzil")}
                onChange={formikProps.handleChange("address")}
              />
              <Input
                placeholder={t("Telefon raqam")}
                onChange={(e) =>
                  formikProps.setFieldValue(
                    "phone",
                    formatPhone(e.target.value)
                  )
                }
                value={formikProps.values.phone}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <Input
                placeholder="INN"
                onChange={(e) =>
                  formikProps.setFieldValue(
                    "inn",
                    e.target.value.replace(/\D/g, "")
                  )
                }
                value={formikProps.values.inn}
              />
              <Input
                placeholder={t("Bank nomi")}
                onChange={formikProps.handleChange("bank_name")}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <Input
                placeholder="MFO"
                onChange={formikProps.handleChange("mfo")}
              />
              <Input
                placeholder="OKED"
                onChange={formikProps.handleChange("oked")}
              />
            </div>
            <Input placeholder={t("Hisob raqam")} onChange={formikProps.handleChange("payment_account")}/>
            <Label className={"mb-2"}>{t("Yetkazib berish")}</Label>
            <div className="grid grid-cols-2 gap-4">
              <select
                onChange={(e) => handleCorpRegionChange(Number(e.target.value))}
                className="w-full p-2 rounded-md border"
              >
                <option value="">{t("Viloyatni tanlang")}</option>
                {regions?.data.map((region) => (
                  <option key={region.id} value={region.id}>
                    {region.name}
                  </option>
                ))}
              </select>

              <select
                onChange={formikProps.handleChange("city_id")}
                className="w-full p-2 rounded-md border"
                disabled={!corpDistricts}
              >
                <option value="">{t("Tuman/shahar")}</option>
                {corpDistricts?.map((district) => (
                  <option key={district.id} value={district.id}>
                    {district.name}
                  </option>
                ))}
              </select>
            </div>
            <Input
              placeholder={t("Manzil")}
              onChange={formikProps.handleChange("address")}
            />
            <Input
              placeholder={t("Uy raqami")}
              onChange={formikProps.handleChange("home")}
            />
            <Input
              placeholder={t("Mo'ljal")}
              onChange={formikProps.handleChange("landmark")}
            />
            <div>
              <Label className="mb-2 block">{t("O‘rnatish xizmati kerakmi?")}</Label>
              <RadioGroup
                onValueChange={(value) =>
                  formikProps.setFieldValue(
                    "with_installation",
                    value === "yes"
                  )
                }
                defaultValue="yes"
                className="flex gap-4"
              >
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="yes" id="c-install-yes" />
                  <Label htmlFor="c-install-yes">{t("Ha")}</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="no" id="c-install-no" />
                  <Label htmlFor="c-install-no">{t("Yo‘q")}</Label>
                </div>
              </RadioGroup>
            </div>

            <div>
              <Label className="mb-2 block">{t("Yetkazib berish kerakmi")}</Label>
              <RadioGroup
                onValueChange={(value) =>
                  formikProps.setFieldValue("delivery_type", value)
                }
                defaultValue="delivery"
                className="flex gap-4"
              >
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="delivery" id="c-install-yes" />
                  <Label htmlFor="c-install-yes">{t("Ha")}</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="pickup" id="c-install-no" />
                  <Label htmlFor="c-install-no">{t("Yo‘q o'zim olib ketaman")}</Label>
                </div>
              </RadioGroup>
            </div>

            <DialogFooter className="mt-4">
              <Button
                size="lg"
                type="submit"
                className="w-full"
                disabled={isOrderCreating}
              >
                {isOrderCreating ? (
                  <Loader2 className="animate-spin" />
                ) : (
                  t("Yuborish")
                )}
              </Button>
            </DialogFooter>

          </TabsContent>
        </Form>
      )}
    </Formik>
  );
};

export default LegalTab;
