"use client";

import {
  Box,
  Button,
  Checkbox,
  Container,
  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 countryOptions = [
  { value: "+966", label: "+966" },
  { value: "+971", label: "+971" },
  { value: "+20", label: "+20" },
];

export default function LoginPage() {
  const [phone, setPhone] = useState("");
  const [countryCode, setCountryCode] = useState("+966");
  const [agree, setAgree] = 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 handleLogin = async () => {
    if (!agree) {
      setDialogMessage("يجب الموافقة على الشروط والأحكام");
      setErrorOpen(true);
      return;
    }

    if (!phone.trim()) {
      setDialogMessage("يرجى إدخال رقم الجوال");
      setErrorOpen(true);
      return;
    }

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

      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 {
        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>

        <Flex gap={12} w="100%" wrap="wrap">
          <Box style={{ flex: 1 }}>
            {/* <Select
              size="md"
              rightSection={<IconChevronDown size={16} />}
              data={countryOptions}
              value={countryCode}
              onChange={(value) => setCountryCode(value!)}
              styles={{
                input: {
                  borderRadius: 12,
                  background: theme.colors.input,
                  textAlign: "right",
                  height: 50,
                  "&:focus": {
                    border: `1px solid ${theme.colors.gold} `,
                  },
                },
              }}
            /> */}
          </Box>

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

        <Checkbox
          color={theme.colors.gold}
          dir="rtl"
          label="الموافقة علي الشروط والاحكام"
          size="xs"
          checked={agree}
          onChange={(e) => setAgree(e.currentTarget.checked)}
        />

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

        <Text ta="center" size="sm" c={theme.colors.gray}>
          ليس لديك حساب؟{" "}
          <Text
            component="a"
            href="/register"
            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>
  );
}
