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 PhysicalTab = ({ product, setIsDialogOpen }: Props) => {
  const t = useTranslations("")
  const { data: regions } = useQuery({
    queryKey: ["getRegions"],
    queryFn: getRegions,
  });

  const [isOrderCreating, setIsOrderCreating] = useState(false);
  const [districts, setDistricts] = useState<
    { id: number; name: string }[] | null
  >(null);
  const handleRegionChange = (regionId: number) => {
    const selectedRegion = regions?.data?.find(
      (region) => region.id === regionId
    );
    setDistricts(selectedRegion?.cities || []);
  };

  return (
    <Formik
      initialValues={{
        full_name: "",
        phone: "+998 ",
        jshir: "",
        series: "",
        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,
          series: 1,
          type: "ready_solutions",
          delivery_type: values.delivery_type,
          client_type: "physical",
          client_information: {
            full_name: values.full_name,
            jshir: values.jshir,
            series: values.series,
            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>
          {/* Physical */}
          <TabsContent value="physical" className="space-y-4 mt-4">
            <div className="grid grid-cols-2 gap-4">
              <Input
                placeholder={t("full_name")}
                onChange={formikProps.handleChange("full_name")}
              />
              {formikProps.errors.full_name && (
                <p className="text-red-500 text-sm">
                  {formikProps.errors.full_name}
                </p>
              )}
              <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="JShShIR"
                value={formikProps.values.jshir}
                onChange={(e) =>
                  formikProps.setFieldValue(
                    "jshir",
                    e.target.value.replace(/\D/g, "")
                  )
                }
              />
              <Input
                placeholder={t("Passport seriya va raqami")}
                onChange={formikProps.handleChange("series")}
              />
            </div>

            <Label className={"mb-2"}>{t("Yetkazib berish")}</Label>
            <div className={"grid grid-cols-2 gap-4"}>
              <select
                onChange={(e) => handleRegionChange(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={!districts}
              >
                <option value="">{t("Tuman/shahar")}</option>
                {districts?.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="install-yes" />
                  <Label htmlFor="install-yes">{t("Ha")}</Label>
                </div>
                <div className="flex items-center gap-2">
                  <RadioGroupItem value="no" id="install-no" />
                  <Label htmlFor="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="yes"
                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 PhysicalTab;
