"use client";

import { useState, useEffect, useRef } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import Image from "next/image";
import { useSendCode, useVerifyCode } from "@/api/usePhoneAuth";

interface AuthDialogProps {
  isOpen: boolean;
  onClose: () => void;
}

type AuthStep = "phone" | "code";

export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
  const [step, setStep] = useState<AuthStep>("phone");
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState(["", "", "", ""]);
  const [error, setError] = useState<string | null>(null);
  const [resendSeconds, setResendSeconds] = useState(0);

  const sendCodeMutation = useSendCode();
  const verifyCodeMutation = useVerifyCode();

  const codeInputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const prevCodeLengthRef = useRef(0);

  useEffect(() => {
    if (!isOpen) {
      setStep("phone");
      setPhone("");
      setCode(["", "", "", ""]);
      setError(null);
      setResendSeconds(0);
      prevCodeLengthRef.current = 0;
    }
  }, [isOpen]);

  // Таймер повторной отправки кода
  useEffect(() => {
    if (step !== "code" || resendSeconds <= 0) return;
    const t = setInterval(() => setResendSeconds((s) => (s <= 0 ? 0 : s - 1)), 1000);
    return () => clearInterval(t);
  }, [step, resendSeconds]);

  const formatPhoneNumber = (value: string): string => {
    const digits = value.replace(/\D/g, "");

    if (digits.length === 0) return "";

    let formatted = "";
    if (digits.length > 0) {
      formatted = `(${digits.slice(0, 3)}`;
    }
    if (digits.length > 3) {
      formatted += `) ${digits.slice(3, 6)}`;
    }
    if (digits.length > 6) {
      formatted += ` ${digits.slice(6, 10)}`;
    }

    return formatted;
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value;
    const digitsOnly = input.replace(/\D/g, "").slice(0, 10);
    setPhone(digitsOnly);
  };

  const handlePhoneSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (phone.length < 10) return;

    setError(null);

    try {
      await sendCodeMutation.mutateAsync({ phone: `7${phone}` });
      setResendSeconds(60);
      setStep("code");

      setTimeout(() => {
        codeInputRefs.current[0]?.focus();
      }, 100);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Не удалось отправить код. Попробуйте позже.");
    }
  };

  const handleCodeChange = (index: number, value: string) => {
    if (!/^\d*$/.test(value)) return;

    const newCode = [...code];
    newCode[index] = value.slice(-1);
    setCode(newCode);

    if (value && index < 3) {
      codeInputRefs.current[index + 1]?.focus();
    }
  };

  const handleCodeKeyDown = (
    index: number,
    e: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (e.key === "Backspace" && !code[index] && index > 0) {
      codeInputRefs.current[index - 1]?.focus();
    }
  };

  const handleCodePaste = (e: React.ClipboardEvent) => {
    e.preventDefault();
    const pastedData = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 4);
    const newCode = [...code];
    for (let i = 0; i < pastedData.length; i++) {
      newCode[i] = pastedData[i];
    }
    setCode(newCode);
    const nextEmptyIndex = newCode.findIndex((c) => !c);
    if (nextEmptyIndex !== -1) {
      codeInputRefs.current[nextEmptyIndex]?.focus();
    } else {
      codeInputRefs.current[3]?.focus();
    }
  };

  const submitCode = async () => {
    const fullCode = code.join("");
    if (fullCode.length !== 4) return;

    setError(null);

    try {
      await verifyCodeMutation.mutateAsync({
        phone: `7${phone}`,
        code: fullCode,
      });
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Неверный код. Попробуйте ещё раз.");
    }
  };

  // Автоотправка кода, когда все 4 поля заполнены
  useEffect(() => {
    if (step !== "code" || verifyCodeMutation.isPending) return;
    const fullCode = code.join("");
    if (fullCode.length === 4 && prevCodeLengthRef.current < 4) {
      prevCodeLengthRef.current = 4;
      submitCode();
    } else {
      prevCodeLengthRef.current = fullCode.length;
    }
  }, [step, code, verifyCodeMutation.isPending]);

  const handleCodeSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    submitCode();
  };

  const getFormattedPhone = () => {
    return `+7 ${phone.slice(0, 3)} ${phone.slice(3)}`;
  };

  const handleResendCode = () => {
    if (resendSeconds > 0) return;
    setResendSeconds(60);
    sendCodeMutation.mutate({ phone: `7${phone}` });
  };

  const LegalText = () => (
    <p className="text-xs text-gray-500 text-center">
      Входя в аккаунт или создавая новый, вы соглашаетесь с нашими{" "}
      <button type="button" className="cursor-pointer text-gray-700 underline hover:text-gray-900">
        Правилами и условиями
      </button>
      {" и "}
      <button type="button" className="cursor-pointer text-gray-700 underline hover:text-gray-900">
        Положением о конфиденциальности
      </button>
    </p>
  );

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="w-full max-w-[100vw] min-w-0 h-full min-h-[100dvh] rounded-none p-0 overflow-hidden bg-white md:min-h-0 md:max-w-4xl md:h-[414px] md:rounded-[30px]">
        <div className="flex h-full items-start md:items-center min-w-0">
          <div className="flex-1 flex flex-col bg-white rounded-l-[30px] py-6 px-4 sm:py-[34px] sm:px-[28px] min-w-0 overflow-auto">
            {step === "phone" ? (
              <>
                <DialogHeader className="text-center">
                  <DialogTitle className="text-2xl font-bold text-black mb-8">
                    Добро пожаловать
                    <br />
                    в Travel Marine
                  </DialogTitle>
                  <p className="text-gray-500 text-base mb-4">
                    Бронируйте яхты и катера, управляйте заказами и используйте все возможности платформы
                  </p>
                </DialogHeader>

                <form onSubmit={handlePhoneSubmit} className="flex flex-col flex-1">
                  <div className="relative">
                    <div className="flex items-center gap-2 px-3 sm:px-4 rounded-full border border-gray-200 overflow-hidden bg-white min-w-0">
                      <div className="flex items-center gap-2 shrink-0">
                        <div className="flex items-center justify-center h-[36px] w-[36px] rounded-[16px] border border-gray-200" aria-hidden><div className="text-xl">🇷🇺</div></div>
                        <span className="text-gray-800 font-medium">+7</span>
                      </div>
                      <input
                        type="tel"
                        value={formatPhoneNumber(phone)}
                        onChange={handlePhoneChange}
                        placeholder="(000) 000 0000"
                        className="flex-1 min-w-0 py-4 outline-none text-gray-800 placeholder:text-gray-400 w-0"
                      />
                      <Button
                        type="submit"
                        disabled={phone.length < 10 || sendCodeMutation.isPending}
                        className="h-[40px] px-4 sm:px-8 bg-brand hover:bg-brand-hover text-white rounded-full font-semibold transition-colors disabled:opacity-50 shrink-0"
                      >
                        Далее
                      </Button>
                    </div>

                    {error && (
                      <p className="absolute left-0 right-0 top-full mt-2 text-red-500 text-xs text-center">{error}</p>
                    )}
                  </div>

                  <div className="mt-11">
                    <LegalText />
                  </div>
                </form>
              </>
            ) : (
              <>
                <DialogHeader className="text-center">
                  <DialogTitle className="text-2xl font-bold text-black mb-8">
                    Подтверждение номера
                  </DialogTitle>
                  <p className="text-gray-500 text-sm">
                    Введите 4-значный код, отправленный на номер:
                  </p>
                  <p className="text-black text-sm font-bold mb-4">{getFormattedPhone()}</p>
                </DialogHeader>

                <form onSubmit={handleCodeSubmit} className="flex flex-col flex-1">
                  <div className="flex justify-center gap-2 relative mb-6">
                    {code.map((digit, index) => (
                      <input
                        key={index}
                        ref={(el) => {
                          codeInputRefs.current[index] = el;
                        }}
                        type="text"
                        inputMode="numeric"
                        maxLength={1}
                        value={digit}
                        onChange={(e) => handleCodeChange(index, e.target.value)}
                        onKeyDown={(e) => handleCodeKeyDown(index, e)}
                        onPaste={handleCodePaste}
                        className="w-14 h-14 text-center text-2xl font-semibold bg-white rounded-[4px] border border-gray-200 focus:border-brand focus:ring-2 focus:ring-brand/20 outline-none transition-all"
                      />
                    ))}
                    {error && (
                      <p className="absolute left-0 right-0 top-full mt-2 text-red-500 text-xs text-center">{error}</p>
                    )}
                  </div>



                  <p className="text-sm text-black text-center mb-1">
                    {resendSeconds > 0 ? (
                      <>Отправить код повторно через {String(Math.floor(resendSeconds / 60)).padStart(2, "0")}:{String(resendSeconds % 60).padStart(2, "0")}</>
                    ) : (
                      <button
                        type="button"
                        onClick={handleResendCode}
                        className="text-brand hover:underline"
                      >
                        Отправить код повторно
                      </button>
                    )}
                  </p>
                  <button
                    type="button"
                    onClick={() => { setStep("phone"); setError(null); setCode(["", "", "", ""]) }}
                    className="text-brand text-sm hover:underline text-center"
                  >
                    Изменить номер
                  </button>

                  <div className="mt-5">
                    <LegalText />
                  </div>
                </form>
              </>
            )}
          </div>

          <div className="hidden md:block w-[45%] h-full flex-shrink-0 py-[34px] pr-[28px] pl-0">
            <div className="relative w-full h-full overflow-hidden rounded-[10px]">
              <Image
                src="/images/auth.png"
                alt="Яхты"
                fill
                className="object-cover"
              />
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
