"use client";

import { Box, Button, Container, Stack, Text, TextInput } from "@mantine/core";
import theme from "@/styles/theme";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { SuccessDialog } from "@/shared/SuccessDialog";
import { ErrorDialog } from "@/shared/ErrorDialog";
import Cookies from "js-cookie";

const CODE_LENGTH = 5;

export default function VerifyPhonePage() {
  const [code, setCode] = useState(Array(CODE_LENGTH).fill(""));
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const [isComplete, setIsComplete] = useState(false);
  const [loading, setLoading] = useState(false);

  const [successOpen, setSuccessOpen] = useState(false);
  const [errorOpen, setErrorOpen] = useState(false);
  const [dialogMessage, setDialogMessage] = useState("");

  const router = useRouter();

  const phone = "0987654321";

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

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

    if (value && index < CODE_LENGTH - 1) {
      inputRefs.current[index + 1]?.focus();
    }
  };

  const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
    const paste = event.clipboardData
      .getData("text")
      .replace(/\D/g, "")
      .slice(0, CODE_LENGTH);
    const newCode = paste.split("");
    for (let i = 0; i < CODE_LENGTH; i++) {
      code[i] = newCode[i] || "";
    }
    setCode([...code]);
    setTimeout(() => {
      const nextEmpty = code.findIndex((v) => !v);
      if (nextEmpty !== -1) {
        inputRefs.current[nextEmpty]?.focus();
      }
    }, 0);
  };

  useEffect(() => {
    setIsComplete(code.every((c) => c !== ""));
  }, [code]);

  const handleSubmit = async () => {
    setLoading(true);
    const otp = code.join("");

    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/investors/set_otp`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ phone, otp }),
        }
      );

      const data = await response.json();

      if (response.ok && data.success) {
        setDialogMessage(data.message || "تم تسجيل الدخول بنجاح");
        setSuccessOpen(true);

        if (data.token) {
          Cookies.set("auth_token", data.token, { expires: 7 });
        }

        setTimeout(() => {
          setSuccessOpen(false);
          router.push("/dashboard");
        }, 2000);
      } else {
        throw new Error(data.message || "رمز التحقق غير صحيح");
      }
    } catch (error: any) {
      setDialogMessage(error.message || "فشل في الاتصال بالخادم");
      setErrorOpen(true);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container
      size={420}
      bg={theme.colors.white}
      px="md"
      py="xl"
      display="flex"
      mih="100vh"
      style={{
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Stack gap="lg" w="100%">
        <Box ta="center">
          <Image
            src="/images/logo.png"
            alt="Logo"
            width={150}
            height={100}
            style={{ margin: "0 auto" }}
          />
        </Box>

        <Box ta="center">
          <Text fw={700} size="xl">
            تأكيد
            <span style={{ color: theme.colors.gold, marginRight: 5 }}>
              رقم الهاتف!
            </span>
          </Text>
        </Box>

        <Box>
          <Text size="md">التحقق من رقم الهاتف</Text>
          <Text size="md" c={theme.colors.gray}>
            قم بكتابة رمز التاكيد الذي تم ارساله إلى {phone}{" "}
            <span style={{ color: theme.colors.purple, cursor: "pointer" }}>
              تعديل
            </span>
          </Text>
        </Box>

        <Box
          display="flex"
          style={{ gap: 12, justifyContent: "center" }}
          dir="ltr"
        >
          {code.map((digit, idx) => (
            <TextInput
              key={idx}
              ref={(el: any) => (inputRefs.current[idx] = el)}
              value={digit}
              onChange={(e) => handleChange(e.target.value, idx)}
              onPaste={handlePaste}
              maxLength={1}
              styles={{
                input: {
                  width: 60,
                  height: 60,
                  textAlign: "center",
                  fontSize: "1.5rem",
                  borderRadius: 8,
                  background: "transparent",
                  color: theme.colors.purple,
                },
              }}
            />
          ))}
        </Box>

        <Button
          fullWidth
          radius="md"
          mt="md"
          bg={theme.colors.darkGray}
          disabled={!isComplete}
          loading={loading}
          onClick={handleSubmit}
        >
          الدخول
        </Button>
      </Stack>

      <SuccessDialog
        opened={successOpen}
        onClose={() => setSuccessOpen(false)}
        message={dialogMessage}
      />

      <ErrorDialog
        opened={errorOpen}
        onClose={() => setErrorOpen(false)}
        message={dialogMessage}
      />
    </Container>
  );
}
