"use client";

import { cn } from "@/shared/lib/utils";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/ui/card";
import { Label } from "@radix-ui/react-label";
import { Input } from "@/shared/ui/input";
import { Button } from "@/shared/ui/button";
import Image from "next/image";
import { FormEvent, useState } from "react";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/shared/ui/input-otp";
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
import { Checkbox } from "@/shared/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/ui/dialog";
import { sendPhoneNumber, verifyCode } from "@/shared/api";
import { useRouter } from "@/shared/config/i18n/navigation";
import { useTranslations } from "next-intl";

const LoginSection = ({
  className,
  ...props
}: React.ComponentPropsWithoutRef<"div">) => {
  const [step, setStep] = useState(1);
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const router = useRouter();
  const t = useTranslations("");

  const handlePhoneSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    await sendPhoneNumber(phone);
    setStep(2);
  };

  const handleVerifySubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    await verifyCode(phone, parseInt(code));
    router.push("/profile");
  };

  return (
    <div className={cn("flex flex-col gap-6", className)} {...props}>
      {step === 1 ? (
        <Card className="shadow-none border-none">
          <CardHeader>
            <Image
              className="mx-auto mb-10"
              src="/getgreen.png"
              alt=""
              width={300}
              height={300}
            />
            <CardTitle className="text-2xl">{t("Login")}</CardTitle>
            <CardDescription>
              {t("Hisobingizga kirish uchun telefon raqamingizni kiriting")}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handlePhoneSubmit}>
              <div className="flex flex-col gap-6">
                <div className="grid gap-2">
                  <Label htmlFor="phone">{t("Telefon")}</Label>
                  <Input
                    id="phone"
                    type="tel"
                    name="phone"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="+998 94 456 78 90"
                    required
                  />
                  <div className="flex items-center space-x-2 mt-2">
                    <Checkbox id="terms" required />
                    {t.rich("terms_of_use", {
                      tag: (chunks) => (
                        <label
                          htmlFor="terms"
                          className="text-sm font-medium leading-none"
                        >
                          <TermsOfUse /> {chunks}
                        </label>
                      ),
                    })}
                  </div>
                </div>
                <Button type="submit" className="w-full">
                  {t("login")}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      ) : (
        <Card className="shadow-none border-none">
          <CardHeader>
            <Image
              className="mx-auto mb-10"
              src="/getgreen.png"
              alt=""
              width={300}
              height={300}
            />
            <CardTitle className="text-2xl">OTP</CardTitle>
            <CardDescription>{t("Tasdiqlash kodini kiriting")}</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleVerifySubmit}>
              <div className="flex flex-col gap-6">
                <div className="grid gap-2">
                  <InputOTP
                    maxLength={5}
                    pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
                    value={code}
                    onChange={setCode}
                  >
                    <InputOTPGroup>
                      {[0, 1, 2, 3, 4].map((i) => (
                        <InputOTPSlot key={i} index={i} />
                      ))}
                    </InputOTPGroup>
                  </InputOTP>
                </div>
                <Button type="submit" className="w-full">
                  {t("Tasdiqlash")}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default LoginSection;

const TermsOfUse = () => {
  const t = useTranslations("")
  return (
    <Dialog>
    <DialogTrigger asChild>
      <span className="border-b border-primary cursor-pointer">
        {t("Offer va shartlar")}
      </span>
    </DialogTrigger>
    <DialogContent className="min-w-6/12">
      <DialogHeader>
        <DialogTitle>{t("Offerta shartlari")}</DialogTitle>
        <DialogDescription>
          {t("Bu yerda offerta shartlarini o'qib chiqishingiz mumkin")}
        </DialogDescription>
      </DialogHeader>
      <div className="overflow-y-scroll h-[70vh]">
        {/* Replace with actual offer content */}
        Lorem ipsum dolor sit amet, consectetur...
      </div>
    </DialogContent>
  </Dialog>
  )
}
