import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Alert,
  Box,
  Button,
  Divider,
  Group,
  Paper,
  PasswordInput,
  Select,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
  ThemeIcon,
  Title,
} from '@mantine/core';
import {
  IconAnchor,
  IconAlertCircle,
  IconCheck,
  IconLock,
  IconMail,
  IconShip,
  IconUser,
} from '@tabler/icons-react';
import { useApiMutation } from '@ema-platform/api';
import { notify, PhoneInput } from '@ema-platform/ui';
import { isValidPhoneNumber } from 'libphonenumber-js';

const OWNER_TYPES = [
  'Individual (Private Owner)',
  'Private Company / PLC',
  'State Enterprise',
  'NGO / Non-Profit',
  'Government Agency',
];

export function VesselOwnerRegisterPage() {
  const navigate = useNavigate();
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [ownerType, setOwnerType] = useState<string | null>(null);
  const [nationalIdOrTin, setNationalIdOrTin] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [registerTrigger] = useApiMutation<{ id: string }>();

  const canSubmit = !!fullName.trim() && !!email.trim() && isValidPhoneNumber(phone) && !!ownerType && !!nationalIdOrTin.trim() && !!password && password === confirmPassword;

  const handleRegister = async () => {
    if (!canSubmit) {
      setError('Please fill in all required fields. Passwords must match.');
      return;
    }
    setError('');
    setLoading(true);
    try {
      await registerTrigger({
        url: '/auth/vessel-owner/register',
        method: 'POST',
        body: { fullName, email, phone, ownerType, nationalIdOrTin, password },
      }).unwrap();
      setSuccess(true);
      notify.success('Account created! You can now sign in.');
    } catch {
      setError('Registration failed. This email may already be registered.');
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <Box style={{ minHeight: '100vh', background: 'var(--mantine-color-gray-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Paper withBorder radius="lg" p="xl" w="100%" maw={440} shadow="sm" mx="md">
          <Stack align="center" gap="md">
            <ThemeIcon size={56} radius="xl" color="teal" variant="light">
              <IconCheck size={30} />
            </ThemeIcon>
            <Title order={3} ta="center">Account Created!</Title>
            <Text fz="sm" c="dimmed" ta="center">
              Your vessel owner account has been created. You can now sign in and submit vessel registration applications.
            </Text>
            <Button fullWidth onClick={() => navigate('/vessel-owner/login')}>
              Sign In Now
            </Button>
          </Stack>
        </Paper>
      </Box>
    );
  }

  return (
    <Box style={{ minHeight: '100vh', background: 'var(--mantine-color-gray-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <Stack align="center" gap="xl" w="100%" maw={540} px="md">
        <Stack align="center" gap="xs">
          <ThemeIcon size={64} radius="xl" color="blue" variant="light">
            <IconShip size={36} />
          </ThemeIcon>
          <Title order={2} ta="center">Create Vessel Owner Account</Title>
          <Text fz="sm" c="dimmed" ta="center">Ethiopian Maritime Affairs Authority</Text>
        </Stack>

        <Paper withBorder radius="lg" p="xl" w="100%" shadow="sm">
          <Group gap="xs" mb="lg">
            <IconAnchor size={20} color="var(--mantine-color-blue-6)" />
            <Text fw={700} fz="lg">Owner Registration</Text>
          </Group>

          {error && (
            <Alert icon={<IconAlertCircle size={16} />} color="red" mb="md">{error}</Alert>
          )}

          <Stack gap="md">
            <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
              <TextInput
                label="Full Name / Company Name"
                placeholder="e.g. Abebe Girma"
                leftSection={<IconUser size={16} />}
                required
                value={fullName}
                onChange={(e) => setFullName(e.currentTarget.value)}
              />
              <Select
                label="Owner Type"
                placeholder="Select type"
                required
                data={OWNER_TYPES}
                value={ownerType}
                onChange={setOwnerType}
              />
              <TextInput
                label="Email Address"
                placeholder="owner@example.com"
                leftSection={<IconMail size={16} />}
                required
                value={email}
                onChange={(e) => setEmail(e.currentTarget.value)}
              />
              <PhoneInput
                label="Phone Number"
                required
                value={phone}
                onChange={setPhone}
              />
              <TextInput
                label="National ID / TIN"
                placeholder="ET-0000000 or TIN"
                required
                value={nationalIdOrTin}
                onChange={(e) => setNationalIdOrTin(e.currentTarget.value)}
              />
            </SimpleGrid>

            <Divider label="Set Password" labelPosition="center" />

            <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
              <PasswordInput
                label="Password"
                placeholder="Min. 8 characters"
                leftSection={<IconLock size={16} />}
                required
                value={password}
                onChange={(e) => setPassword(e.currentTarget.value)}
              />
              <PasswordInput
                label="Confirm Password"
                placeholder="Repeat password"
                leftSection={<IconLock size={16} />}
                required
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.currentTarget.value)}
                error={confirmPassword && password !== confirmPassword ? 'Passwords do not match' : undefined}
              />
            </SimpleGrid>

            <Button fullWidth size="md" loading={loading} disabled={!canSubmit} onClick={handleRegister}>
              Create Account
            </Button>
          </Stack>

          <Divider my="md" label="Already have an account?" labelPosition="center" />
          <Button fullWidth variant="light" onClick={() => navigate('/vessel-owner/login')}>
            Sign In
          </Button>
        </Paper>
      </Stack>
    </Box>
  );
}
