"use client";

import {
  Box,
  Button,
  Container,
  FileInput,
  Flex,
  Select,
  Stack,
  Text,
  TextInput,
} from "@mantine/core";
import theme from "@/styles/theme";
import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { SuccessDialog } from "@/shared/SuccessDialog";
import { ErrorDialog } from "@/shared/ErrorDialog";

const idTypeOptions = [
  { value: "national_id", label: "الهوية الوطنية" },
  { value: "iqama", label: "الإقامة" },
  { value: "passport", label: "جواز السفر" },
];

export default function RegisterPage() {
  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    email: "",
    address: "",
    id_type: "",
    id_number: "",
  });
  const [image, setImage] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);

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

  const router = useRouter();

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async () => {
    const requiredFields = [
      "name",
      "phone",
      "email",
      "address",
      "id_type",
      "id_number",
    ];
    const missingFields = requiredFields.filter(
      (field) => !formData[field as keyof typeof formData]
    );

    if (missingFields.length > 0) {
      setDialogMessage("يرجى ملء جميع الحقول المطلوبة");
      setErrorOpen(true);
      return;
    }

    if (!image) {
      setDialogMessage("يرجى إرفاق صورة الهوية");
      setErrorOpen(true);
      return;
    }

    setLoading(true);
    try {
      const formDataToSend = new FormData();
      Object.entries(formData).forEach(([key, value]) => {
        formDataToSend.append(key, value);
      });
      if (image) {
        formDataToSend.append("image", image);
      }

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/investors/register`,
        {
          method: "POST",
          body: formDataToSend,
        }
      );

      const data = await response.json();

      if (response.ok && data.success) {
        setDialogMessage(data.message || "تم إنشاء الحساب بنجاح");
        setSuccessOpen(true);
        setTimeout(() => {
          setSuccessOpen(false);
          router.push("/verify-phone-page");
        }, 2000);
      } else {
        if (data.errors) {
          const errorMessages = Object.values(data.errors).flat().join("\n");
          throw new Error(errorMessages);
        }
        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>

        <Text c={theme.colors.gray} ta="center">
          انشاء حساب جديد
        </Text>

        <TextInput
          size="md"
          placeholder="الاسم الكامل"
          value={formData.name}
          onChange={(e) => handleChange("name", e.target.value)}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <TextInput
          size="md"
          placeholder="رقم الجوال"
          value={formData.phone}
          onChange={(e) => handleChange("phone", e.target.value)}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <TextInput
          size="md"
          placeholder="البريد الإلكتروني"
          value={formData.email}
          onChange={(e) => handleChange("email", e.target.value)}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <TextInput
          size="md"
          placeholder="العنوان"
          value={formData.address}
          onChange={(e) => handleChange("address", e.target.value)}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <Select
          size="md"
          placeholder="نوع الهوية"
          data={idTypeOptions}
          value={formData.id_type}
          onChange={(value) => handleChange("id_type", value || "")}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <TextInput
          size="md"
          placeholder="رقم الهوية"
          value={formData.id_number}
          onChange={(e) => handleChange("id_number", e.target.value)}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <FileInput
          placeholder="صورة الهوية"
          accept="image/*"
          value={image}
          onChange={setImage}
          styles={{
            input: {
              borderRadius: 12,
              background: theme.colors.input,
              height: 50,
              "&:focus": {
                border: `1px solid ${theme.colors.gold}`,
              },
            },
          }}
        />

        <Button
          bg={theme.colors.darkGray}
          fullWidth
          radius="md"
          mt="md"
          onClick={handleSubmit}
          loading={loading}
        >
          انشاء حساب
        </Button>

        <Text ta="center" size="sm" c={theme.colors.gray}>
          لديك حساب بالفعل؟{" "}
          <Text
            component="a"
            href="/login"
            span
            c={theme.colors.gold}
            style={{ textDecoration: "none", cursor: "pointer" }}
          >
            تسجيل الدخول
          </Text>
        </Text>
      </Stack>

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

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