'use client';

import React from 'react';
import {
  Mail,
  Lock,
  Eye,
  EyeOff,
  UserPlus,
  AlertCircle,
  Flag,
  User,
  Check,
  X,
  Car,
  Users,
  Trophy,
  Shield,
  Sparkles,
} from 'lucide-react';
import { Card } from '@/ui/Card';
import { Button } from '@/ui/Button';
import { Input } from '@/ui/Input';
import { Heading } from '@/ui/Heading';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Link } from '@/ui/Link';
import { Surface } from '@/ui/Surface';
import { Icon } from '@/ui/Icon';
import { LoadingSpinner } from '@/ui/LoadingSpinner';
import { SignupViewData } from '@/lib/builders/view-data/types/SignupViewData';
import { checkPasswordStrength } from '@/lib/utils/validation';

interface SignupTemplateProps {
  viewData: SignupViewData;
  formActions: {
    handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
    handleSubmit: (e: React.FormEvent<HTMLFormElement>) => Promise<void>;
    setShowPassword: (show: boolean) => void;
    setShowConfirmPassword: (show: boolean) => void;
  };
  uiState: {
    showPassword: boolean;
    showConfirmPassword: boolean;
  };
  mutationState: {
    isPending: boolean;
    error: string | null;
  };
}

const USER_ROLES = [
  {
    icon: Car,
    title: 'Driver',
    description: 'Race, track stats, join teams',
    color: '#3b82f6',
  },
  {
    icon: Trophy,
    title: 'League Admin',
    description: 'Organize leagues and events',
    color: '#10b981',
  },
  {
    icon: Users,
    title: 'Team Manager',
    description: 'Manage team and drivers',
    color: '#a855f7',
  },
];

const FEATURES = [
  'Track your racing statistics and progress',
  'Join or create competitive leagues',
  'Build or join racing teams',
  'Connect your iRacing account',
  'Compete in organized events',
  'Access detailed performance analytics',
];

export function SignupTemplate({ viewData, formActions, uiState, mutationState }: SignupTemplateProps) {
  const passwordStrength = checkPasswordStrength(viewData.formState.fields.password.value);

  const passwordRequirements = [
    { met: viewData.formState.fields.password.value.length >= 8, label: 'At least 8 characters' },
    { met: /[a-z]/.test(viewData.formState.fields.password.value) && /[A-Z]/.test(viewData.formState.fields.password.value), label: 'Upper and lowercase letters' },
    { met: /\d/.test(viewData.formState.fields.password.value), label: 'At least one number' },
    { met: /[^a-zA-Z\d]/.test(viewData.formState.fields.password.value), label: 'At least one special character' },
  ];

  return (
    <Box as="main" style={{ minHeight: '100vh', display: 'flex', position: 'relative' }}>
      {/* Background Pattern */}
      <Box style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom right, rgba(59, 130, 246, 0.05), transparent, rgba(147, 51, 234, 0.05))' }} />
      
      {/* Left Side - Info Panel (Hidden on mobile) */}
      <Box className="hidden lg:flex lg:w-1/2" style={{ position: 'relative', alignItems: 'center', justifyContent: 'center', padding: '3rem' }}>
        <Box style={{ maxWidth: '32rem' }}>
          {/* Logo */}
          <Stack direction="row" align="center" gap={3} mb={8}>
            <Surface variant="muted" rounded="xl" border padding={2} style={{ backgroundColor: 'rgba(59, 130, 246, 0.1)', borderColor: 'rgba(59, 130, 246, 0.3)' }}>
              <Icon icon={Flag} size={6} color="#3b82f6" />
            </Surface>
            <Text size="2xl" weight="bold" color="text-white">GridPilot</Text>
          </Stack>

          <Box mb={4}>
            <Heading level={2}>Start Your Racing Journey</Heading>
          </Box>
          
          <Text size="lg" color="text-gray-400" block mb={8}>
            Join thousands of sim racers. One account gives you access to all roles - race as a driver, organize leagues, or manage teams.
          </Text>

          {/* Role Cards */}
          <Stack gap={3} mb={8}>
            {USER_ROLES.map((role) => (
              <Surface
                key={role.title}
                variant="muted"
                rounded="xl"
                border
                padding={4}
                style={{ backgroundColor: 'rgba(38, 38, 38, 0.3)', borderColor: '#262626' }}
              >
                <Stack direction="row" align="center" gap={4}>
                  <Surface variant="muted" rounded="lg" padding={2} style={{ backgroundColor: `${role.color}1A` }}>
                    <Icon icon={role.icon} size={5} color={role.color} />
                  </Surface>
                  <Box>
                    <Text weight="medium" color="text-white" block>{role.title}</Text>
                    <Text size="sm" color="text-gray-500" block mt={1}>{role.description}</Text>
                  </Box>
                </Stack>
              </Surface>
            ))}
          </Stack>

          {/* Features List */}
          <Box mb={8}>
            <Surface variant="muted" rounded="xl" border padding={5} style={{ backgroundColor: 'rgba(38, 38, 38, 0.2)', borderColor: '#262626' }}>
              <Stack direction="row" align="center" gap={2} mb={4}>
                <Icon icon={Sparkles} size={4} color="#3b82f6" />
                <Text size="sm" weight="medium" color="text-white">What you&apos;ll get</Text>
              </Stack>
              <Stack gap={2}>
                {FEATURES.map((feature, index) => (
                  <Stack key={index} direction="row" align="center" gap={2}>
                    <Icon icon={Check} size={3.5} color="#10b981" />
                    <Text size="sm" color="text-gray-400">{feature}</Text>
                  </Stack>
                ))}
              </Stack>
            </Surface>
          </Box>

          {/* Trust Indicators */}
          <Stack direction="row" align="center" gap={6}>
            <Stack direction="row" align="center" gap={2}>
              <Icon icon={Shield} size={4} color="#737373" />
              <Text size="sm" color="text-gray-500">Secure signup</Text>
            </Stack>
            <Text size="sm" color="text-gray-500">iRacing integration</Text>
          </Stack>
        </Box>
      </Box>

      {/* Right Side - Signup Form */}
      <Box style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '3rem 1rem', position: 'relative', overflowY: 'auto' }}>
        <Box style={{ width: '100%', maxWidth: '28rem' }}>
          {/* Mobile Logo/Header */}
          <Box className="lg:hidden" style={{ textAlign: 'center' }} mb={8}>
            <Surface variant="muted" rounded="2xl" border padding={4} style={{ width: '4rem', height: '4rem', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 1rem' }}>
              <Icon icon={Flag} size={8} color="#3b82f6" />
            </Surface>
            <Heading level={1}>Join GridPilot</Heading>
            <Text color="text-gray-400" block mt={2}>
              Create your account and start racing
            </Text>
          </Box>

          {/* Desktop Header */}
          <Box className="hidden lg:block" style={{ textAlign: 'center' }} mb={8}>
            <Heading level={2}>Create Account</Heading>
            <Text color="text-gray-400" block mt={2}>
              Get started with your free account
            </Text>
          </Box>

          <Card style={{ position: 'relative', overflow: 'hidden' }}>
            {/* Background accent */}
            <Box style={{ position: 'absolute', top: 0, right: 0, width: '8rem', height: '8rem', background: 'linear-gradient(to bottom left, rgba(59, 130, 246, 0.1), transparent)', borderBottomLeftRadius: '9999px' }} />

            <form onSubmit={formActions.handleSubmit}>
              <Stack gap={4} style={{ position: 'relative' }}>
                {/* First Name */}
                <Box>
                  <Text size="sm" weight="medium" color="text-gray-300" block mb={2}>
                    First Name
                  </Text>
                  <Box position="relative">
                    <Box style={{ position: 'absolute', left: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10 }}>
                      <Icon icon={User} size={4} color="#6b7280" />
                    </Box>
                    <Input
                      id="firstName"
                      name="firstName"
                      type="text"
                      value={viewData.formState.fields.firstName.value}
                      onChange={formActions.handleChange}
                      variant={viewData.formState.fields.firstName.error ? 'error' : 'default'}
                      placeholder="John"
                      disabled={mutationState.isPending}
                      style={{ paddingLeft: '2.5rem' }}
                      autoComplete="given-name"
                    />
                  </Box>
                  {viewData.formState.fields.firstName.error && (
                    <Text size="xs" color="text-error-red" block mt={1}>
                      {viewData.formState.fields.firstName.error}
                    </Text>
                  )}
                </Box>

                {/* Last Name */}
                <Box>
                  <Text size="sm" weight="medium" color="text-gray-300" block mb={2}>
                    Last Name
                  </Text>
                  <Box position="relative">
                    <Box style={{ position: 'absolute', left: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10 }}>
                      <Icon icon={User} size={4} color="#6b7280" />
                    </Box>
                    <Input
                      id="lastName"
                      name="lastName"
                      type="text"
                      value={viewData.formState.fields.lastName.value}
                      onChange={formActions.handleChange}
                      variant={viewData.formState.fields.lastName.error ? 'error' : 'default'}
                      placeholder="Smith"
                      disabled={mutationState.isPending}
                      style={{ paddingLeft: '2.5rem' }}
                      autoComplete="family-name"
                    />
                  </Box>
                  {viewData.formState.fields.lastName.error && (
                    <Text size="xs" color="text-error-red" block mt={1}>
                      {viewData.formState.fields.lastName.error}
                    </Text>
                  )}
                  <Text size="xs" color="text-gray-500" block mt={1}>Your name will be used as-is and cannot be changed later</Text>
                </Box>

                {/* Name Immutability Warning */}
                <Surface variant="muted" rounded="lg" border padding={3} style={{ backgroundColor: 'rgba(245, 158, 11, 0.1)', borderColor: 'rgba(245, 158, 11, 0.3)' }}>
                  <Stack direction="row" align="start" gap={3}>
                    <Icon icon={AlertCircle} size={5} color="#f59e0b" />
                    <Text size="sm" color="text-warning-amber">
                      <Text weight="bold">Important:</Text> Your name cannot be changed after signup. Please ensure it's correct.
                    </Text>
                  </Stack>
                </Surface>

                {/* Email */}
                <Box>
                  <Text size="sm" weight="medium" color="text-gray-300" block mb={2}>
                    Email Address
                  </Text>
                  <Box position="relative">
                    <Box style={{ position: 'absolute', left: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10 }}>
                      <Icon icon={Mail} size={4} color="#6b7280" />
                    </Box>
                    <Input
                      id="email"
                      name="email"
                      type="email"
                      value={viewData.formState.fields.email.value}
                      onChange={formActions.handleChange}
                      variant={viewData.formState.fields.email.error ? 'error' : 'default'}
                      placeholder="you@example.com"
                      disabled={mutationState.isPending}
                      style={{ paddingLeft: '2.5rem' }}
                      autoComplete="email"
                    />
                  </Box>
                  {viewData.formState.fields.email.error && (
                    <Text size="xs" color="text-error-red" block mt={1}>
                      {viewData.formState.fields.email.error}
                    </Text>
                  )}
                </Box>

                {/* Password */}
                <Box>
                  <Text size="sm" weight="medium" color="text-gray-300" block mb={2}>
                    Password
                  </Text>
                  <Box position="relative">
                    <Box style={{ position: 'absolute', left: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10 }}>
                      <Icon icon={Lock} size={4} color="#6b7280" />
                    </Box>
                    <Input
                      id="password"
                      name="password"
                      type={uiState.showPassword ? 'text' : 'password'}
                      value={viewData.formState.fields.password.value}
                      onChange={formActions.handleChange}
                      variant={viewData.formState.fields.password.error ? 'error' : 'default'}
                      placeholder="••••••••"
                      disabled={mutationState.isPending}
                      style={{ paddingLeft: '2.5rem', paddingRight: '2.5rem' }}
                      autoComplete="new-password"
                    />
                    <Box
                      as="button"
                      type="button"
                      onClick={() => formActions.setShowPassword(!uiState.showPassword)}
                      style={{ position: 'absolute', right: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10, backgroundColor: 'transparent', border: 'none', cursor: 'pointer' }}
                    >
                      <Icon icon={uiState.showPassword ? EyeOff : Eye} size={4} color="#6b7280" />
                    </Box>
                  </Box>
                  {viewData.formState.fields.password.error && (
                    <Text size="xs" color="text-error-red" block mt={1}>
                      {viewData.formState.fields.password.error}
                    </Text>
                  )}

                  {/* Password Strength */}
                  {viewData.formState.fields.password.value && (
                    <Box mt={3}>
                      <Stack direction="row" align="center" gap={2} mb={2}>
                        <Box style={{ flex: 1, height: '0.375rem', borderRadius: '9999px', backgroundColor: '#262626', overflow: 'hidden' }}>
                          <Box style={{ height: '100%', width: `${(passwordStrength.score / 5) * 100}%`, backgroundColor: passwordStrength.color === 'bg-red-500' ? '#ef4444' : passwordStrength.color === 'bg-yellow-500' ? '#f59e0b' : passwordStrength.color === 'bg-blue-500' ? '#3b82f6' : '#10b981' }} />
                        </Box>
                        <Text size="xs" weight="medium" style={{ color: passwordStrength.color === 'bg-red-500' ? '#f87171' : passwordStrength.color === 'bg-yellow-500' ? '#fbbf24' : passwordStrength.color === 'bg-blue-500' ? '#60a5fa' : '#34d399' }}>
                          {passwordStrength.label}
                        </Text>
                      </Stack>
                      <Box style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: '0.25rem' }}>
                        {passwordRequirements.map((req, index) => (
                          <Stack key={index} direction="row" align="center" gap={1.5}>
                            <Icon icon={req.met ? Check : X} size={3} color={req.met ? '#10b981' : '#525252'} />
                            <Text size="xs" color={req.met ? 'text-gray-300' : 'text-gray-500'}>
                              {req.label}
                            </Text>
                          </Stack>
                        ))}
                      </Box>
                    </Box>
                  )}
                </Box>

                {/* Confirm Password */}
                <Box>
                  <Text size="sm" weight="medium" color="text-gray-300" block mb={2}>
                    Confirm Password
                  </Text>
                  <Box position="relative">
                    <Box style={{ position: 'absolute', left: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10 }}>
                      <Icon icon={Lock} size={4} color="#6b7280" />
                    </Box>
                    <Input
                      id="confirmPassword"
                      name="confirmPassword"
                      type={uiState.showConfirmPassword ? 'text' : 'password'}
                      value={viewData.formState.fields.confirmPassword.value}
                      onChange={formActions.handleChange}
                      variant={viewData.formState.fields.confirmPassword.error ? 'error' : 'default'}
                      placeholder="••••••••"
                      disabled={mutationState.isPending}
                      style={{ paddingLeft: '2.5rem', paddingRight: '2.5rem' }}
                      autoComplete="new-password"
                    />
                    <Box
                      as="button"
                      type="button"
                      onClick={() => formActions.setShowConfirmPassword(!uiState.showConfirmPassword)}
                      style={{ position: 'absolute', right: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10, backgroundColor: 'transparent', border: 'none', cursor: 'pointer' }}
                    >
                      <Icon icon={uiState.showConfirmPassword ? EyeOff : Eye} size={4} color="#6b7280" />
                    </Box>
                  </Box>
                  {viewData.formState.fields.confirmPassword.error && (
                    <Text size="xs" color="text-error-red" block mt={1}>
                      {viewData.formState.fields.confirmPassword.error}
                    </Text>
                  )}
                  {viewData.formState.fields.confirmPassword.value && viewData.formState.fields.password.value === viewData.formState.fields.confirmPassword.value && (
                    <Stack direction="row" align="center" gap={1} mt={1}>
                      <Icon icon={Check} size={3} color="#10b981" />
                      <Text size="xs" color="text-performance-green">Passwords match</Text>
                    </Stack>
                  )}
                </Box>

                {/* Submit Button */}
                <Button
                  type="submit"
                  variant="primary"
                  disabled={mutationState.isPending}
                  fullWidth
                  icon={mutationState.isPending ? <LoadingSpinner size={4} color="white" /> : <Icon icon={UserPlus} size={4} />}
                >
                  {mutationState.isPending ? 'Creating account...' : 'Create Account'}
                </Button>
              </Stack>
            </form>

            {/* Divider */}
            <Box style={{ position: 'relative' }} my={6}>
              <Box style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center' }}>
                <Box style={{ width: '100%', borderTop: '1px solid #262626' }} />
              </Box>
              <Box style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
                <Box px={4} style={{ backgroundColor: '#171717' }}>
                  <Text size="xs" color="text-gray-500">or continue with</Text>
                </Box>
              </Box>
            </Box>

            {/* Login Link */}
            <Box style={{ textAlign: 'center' }} mt={6}>
              <Text size="sm" color="text-gray-400">
                Already have an account?{' '}
                <Link
                  href={viewData.returnTo && viewData.returnTo !== '/onboarding' ? `/auth/login?returnTo=${encodeURIComponent(viewData.returnTo)}` : '/auth/login'}
                >
                  <Text color="text-primary-blue" weight="medium">Sign in</Text>
                </Link>
              </Text>
            </Box>
          </Card>

          {/* Footer */}
          <Box mt={6} style={{ textAlign: 'center' }}>
            <Text size="xs" color="text-gray-500">
              By creating an account, you agree to our{' '}
              <Link href="/terms">
                <Text color="text-gray-400">Terms of Service</Text>
              </Link>
              {' '}and{' '}
              <Link href="/privacy">
                <Text color="text-gray-400">Privacy Policy</Text>
              </Link>
            </Text>
          </Box>

          {/* Mobile Role Info */}
          <Box mt={8} className="lg:hidden">
            <Text size="xs" color="text-gray-500" block mb={4} style={{ textAlign: 'center' }}>One account for all roles</Text>
            <Stack direction="row" align="center" justify="center" gap={6}>
              {USER_ROLES.map((role) => (
                <Stack key={role.title} align="center" gap={1}>
                  <Surface variant="muted" rounded="lg" padding={2} style={{ backgroundColor: `${role.color}1A` }}>
                    <Icon icon={role.icon} size={4} color={role.color} />
                  </Surface>
                  <Text size="xs" color="text-gray-500">{role.title}</Text>
                </Stack>
              ))}
            </Stack>
          </Box>
        </Box>
      </Box>
    </Box>
  );
}
