/**
 * Signup Template
 * 
 * Pure presentation component that accepts ViewData only.
 * No business logic, no state management.
 */

'use client';

import Link from 'next/link';
import { motion } from 'framer-motion';
import {
  Mail,
  Lock,
  Eye,
  EyeOff,
  UserPlus,
  AlertCircle,
  Flag,
  User,
  Check,
  X,
  Car,
  Users,
  Trophy,
  Shield,
  Sparkles,
} from 'lucide-react';

import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
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: 'primary-blue',
  },
  {
    icon: Trophy,
    title: 'League Admin',
    description: 'Organize leagues and events',
    color: 'performance-green',
  },
  {
    icon: Users,
    title: 'Team Manager',
    description: 'Manage team and drivers',
    color: 'purple-400',
  },
];

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 (
    <main className="min-h-screen bg-deep-graphite flex">
      {/* Background Pattern */}
      <div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
      <div className="absolute inset-0 opacity-5">
        <div className="absolute inset-0" style={{
          backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        }} />
      </div>

      {/* Left Side - Info Panel (Hidden on mobile) */}
      <div className="hidden lg:flex lg:w-1/2 relative items-center justify-center p-12">
        <div className="max-w-lg">
          {/* Logo */}
          <div className="flex items-center gap-3 mb-8">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30">
              <Flag className="w-6 h-6 text-primary-blue" />
            </div>
            <span className="text-2xl font-bold text-white">GridPilot</span>
          </div>

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

          {/* Role Cards */}
          <div className="space-y-3 mb-8">
            {USER_ROLES.map((role, index) => (
              <motion.div
                key={role.title}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: index * 0.1 }}
                className="flex items-center gap-4 p-4 rounded-xl bg-iron-gray/50 border border-charcoal-outline"
              >
                <div className={`w-10 h-10 rounded-lg bg-${role.color}/20 flex items-center justify-center`}>
                  <role.icon className={`w-5 h-5 text-${role.color}`} />
                </div>
                <div>
                  <h4 className="text-white font-medium">{role.title}</h4>
                  <p className="text-sm text-gray-500">{role.description}</p>
                </div>
              </motion.div>
            ))}
          </div>

          {/* Features List */}
          <div className="bg-iron-gray/30 rounded-xl border border-charcoal-outline p-5 mb-8">
            <div className="flex items-center gap-2 mb-4">
              <Sparkles className="w-4 h-4 text-primary-blue" />
              <span className="text-sm font-medium text-white">What you'll get</span>
            </div>
            <ul className="space-y-2">
              {FEATURES.map((feature, index) => (
                <li
                  key={index}
                  className="flex items-center gap-2 text-sm text-gray-400"
                >
                  <Check className="w-3.5 h-3.5 text-performance-green flex-shrink-0" />
                  {feature}
                </li>
              ))}
            </ul>
          </div>

          {/* Trust Indicators */}
          <div className="flex items-center gap-6 text-sm text-gray-500">
            <div className="flex items-center gap-2">
              <Shield className="w-4 h-4" />
              <span>Secure signup</span>
            </div>
            <div className="flex items-center gap-2">
              <span>iRacing integration</span>
            </div>
          </div>
        </div>
      </div>

      {/* Right Side - Signup Form */}
      <div className="flex-1 flex items-center justify-center px-4 py-12 overflow-y-auto">
        <div className="relative w-full max-w-md">
          {/* Mobile Logo/Header */}
          <div className="text-center mb-8 lg:hidden">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
              <Flag className="w-8 h-8 text-primary-blue" />
            </div>
            <Heading level={1} className="mb-2">Join GridPilot</Heading>
            <p className="text-gray-400">
              Create your account and start racing
            </p>
          </div>

          {/* Desktop Header */}
          <div className="hidden lg:block text-center mb-8">
            <Heading level={2} className="mb-2">Create Account</Heading>
            <p className="text-gray-400">
              Get started with your free account
            </p>
          </div>

          <Card className="relative overflow-hidden">
            {/* Background accent */}
            <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />

            <form onSubmit={formActions.handleSubmit} className="relative space-y-4">
              {/* First Name */}
              <div>
                <label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
                  First Name
                </label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="firstName"
                    name="firstName"
                    type="text"
                    value={viewData.formState.fields.firstName.value}
                    onChange={formActions.handleChange}
                    error={!!viewData.formState.fields.firstName.error}
                    errorMessage={viewData.formState.fields.firstName.error}
                    placeholder="John"
                    disabled={mutationState.isPending}
                    className="pl-10"
                    autoComplete="given-name"
                  />
                </div>
              </div>

              {/* Last Name */}
              <div>
                <label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
                  Last Name
                </label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="lastName"
                    name="lastName"
                    type="text"
                    value={viewData.formState.fields.lastName.value}
                    onChange={formActions.handleChange}
                    error={!!viewData.formState.fields.lastName.error}
                    errorMessage={viewData.formState.fields.lastName.error}
                    placeholder="Smith"
                    disabled={mutationState.isPending}
                    className="pl-10"
                    autoComplete="family-name"
                  />
                </div>
                <p className="mt-1 text-xs text-gray-500">Your name will be used as-is and cannot be changed later</p>
              </div>

              {/* Name Immutability Warning */}
              <div className="flex items-start gap-3 p-3 rounded-lg bg-warning-amber/10 border border-warning-amber/30">
                <AlertCircle className="w-5 h-5 text-warning-amber flex-shrink-0 mt-0.5" />
                <div className="text-sm text-warning-amber">
                  <strong>Important:</strong> Your name cannot be changed after signup. Please ensure it's correct.
                </div>
              </div>

              {/* Email */}
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
                  Email Address
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="email"
                    name="email"
                    type="email"
                    value={viewData.formState.fields.email.value}
                    onChange={formActions.handleChange}
                    error={!!viewData.formState.fields.email.error}
                    errorMessage={viewData.formState.fields.email.error}
                    placeholder="you@example.com"
                    disabled={mutationState.isPending}
                    className="pl-10"
                    autoComplete="email"
                  />
                </div>
              </div>

              {/* Password */}
              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-2">
                  Password
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="password"
                    name="password"
                    type={uiState.showPassword ? 'text' : 'password'}
                    value={viewData.formState.fields.password.value}
                    onChange={formActions.handleChange}
                    error={!!viewData.formState.fields.password.error}
                    errorMessage={viewData.formState.fields.password.error}
                    placeholder="••••••••"
                    disabled={mutationState.isPending}
                    className="pl-10 pr-10"
                    autoComplete="new-password"
                  />
                  <button
                    type="button"
                    onClick={() => formActions.setShowPassword(!uiState.showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
                  >
                    {uiState.showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>

                {/* Password Strength */}
                {viewData.formState.fields.password.value && (
                  <div className="mt-3 space-y-2">
                    <div className="flex items-center gap-2">
                      <div className="flex-1 h-1.5 rounded-full bg-charcoal-outline overflow-hidden">
                        <motion.div
                          className={`h-full ${passwordStrength.color}`}
                          initial={{ width: 0 }}
                          animate={{ width: `${(passwordStrength.score / 5) * 100}%` }}
                          transition={{ duration: 0.3 }}
                        />
                      </div>
                      <span className={`text-xs font-medium ${
                        passwordStrength.score <= 1 ? 'text-red-400' :
                        passwordStrength.score <= 2 ? 'text-warning-amber' :
                        passwordStrength.score <= 3 ? 'text-primary-blue' :
                        'text-performance-green'
                      }`}>
                        {passwordStrength.label}
                      </span>
                    </div>
                    <div className="grid grid-cols-2 gap-1">
                      {passwordRequirements.map((req, index) => (
                        <div key={index} className="flex items-center gap-1.5 text-xs">
                          {req.met ? (
                            <Check className="w-3 h-3 text-performance-green" />
                          ) : (
                            <X className="w-3 h-3 text-gray-500" />
                          )}
                          <span className={req.met ? 'text-gray-300' : 'text-gray-500'}>
                            {req.label}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* Confirm Password */}
              <div>
                <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-300 mb-2">
                  Confirm Password
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="confirmPassword"
                    name="confirmPassword"
                    type={uiState.showConfirmPassword ? 'text' : 'password'}
                    value={viewData.formState.fields.confirmPassword.value}
                    onChange={formActions.handleChange}
                    error={!!viewData.formState.fields.confirmPassword.error}
                    errorMessage={viewData.formState.fields.confirmPassword.error}
                    placeholder="••••••••"
                    disabled={mutationState.isPending}
                    className="pl-10 pr-10"
                    autoComplete="new-password"
                  />
                  <button
                    type="button"
                    onClick={() => formActions.setShowConfirmPassword(!uiState.showConfirmPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
                  >
                    {uiState.showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
                {viewData.formState.fields.confirmPassword.value && viewData.formState.fields.password.value === viewData.formState.fields.confirmPassword.value && (
                  <p className="mt-1 text-xs text-performance-green flex items-center gap-1">
                    <Check className="w-3 h-3" /> Passwords match
                  </p>
                )}
              </div>

              {/* Submit Button */}
              <Button
                type="submit"
                variant="primary"
                disabled={mutationState.isPending}
                className="w-full flex items-center justify-center gap-2"
              >
                {mutationState.isPending ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Creating account...
                  </>
                ) : (
                  <>
                    <UserPlus className="w-4 h-4" />
                    Create Account
                  </>
                )}
              </Button>
            </form>

            {/* Divider */}
            <div className="relative my-6">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-charcoal-outline" />
              </div>
              <div className="relative flex justify-center text-xs">
                <span className="px-4 bg-iron-gray text-gray-500">or continue with</span>
              </div>
            </div>

            {/* Login Link */}
            <p className="mt-6 text-center text-sm text-gray-400">
              Already have an account?{' '}
              <Link
                href={viewData.returnTo && viewData.returnTo !== '/onboarding' ? `/auth/login?returnTo=${encodeURIComponent(viewData.returnTo)}` : '/auth/login'}
                className="text-primary-blue hover:underline font-medium"
              >
                Sign in
              </Link>
            </p>
          </Card>

          {/* Footer */}
          <p className="mt-6 text-center text-xs text-gray-500">
            By creating an account, you agree to our{' '}
            <Link href="/terms" className="text-gray-400 hover:underline">Terms of Service</Link>
            {' '}and{' '}
            <Link href="/privacy" className="text-gray-400 hover:underline">Privacy Policy</Link>
          </p>

          {/* Mobile Role Info */}
          <div className="mt-8 lg:hidden">
            <p className="text-center text-xs text-gray-500 mb-4">One account for all roles</p>
            <div className="flex justify-center gap-6">
              {USER_ROLES.map((role) => (
                <div key={role.title} className="flex flex-col items-center">
                  <div className={`w-8 h-8 rounded-lg bg-${role.color}/20 flex items-center justify-center mb-1`}>
                    <role.icon className={`w-4 h-4 text-${role.color}`} />
                  </div>
                  <span className="text-xs text-gray-500">{role.title}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}