'use client'

import React, { Suspense, useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useRouter, useSearchParams } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Eye, EyeOff, Loader2, Info, GraduationCap } from 'lucide-react'
import { BRAND } from '@/lib/constants'

const gradeLabels: Record<number, string> = {
  8: 'Grade 8',
  9: 'Grade 9',
  10: 'Grade 10',
  11: 'Grade 11',
  12: 'Grade 12',
  13: 'Post-Matric',
}

const howHeardOptions = [
  'Social Media',
  'Google Search',
  'Friend / Family',
  'Teacher / School',
  'Career Counsellor',
  'Radio / TV',
  'Other',
]

function RegisterForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const assessmentResult = searchParams.get('assessment')

  const [loading, setLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [selectedSubjects, setSelectedSubjects] = useState<string[]>([])

  // Form state
  const [form, setForm] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    password: '',
    gender: '',
    dateOfBirth: '',
    grade: '',
    province: '',
    city: '',
    suburb: '',
    schoolName: '',
    parentEmail: '',
    parentPhone: '',
    howHeard: '',
  })

  const updateForm = (field: string, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }))
  }

  const toggleSubject = (subject: string) => {
    setSelectedSubjects((prev) =>
      prev.includes(subject) ? prev.filter((s) => s !== subject) : [...prev, subject]
    )
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    await new Promise((resolve) => setTimeout(resolve, 1500))
    setLoading(false)
    router.push('/dashboard')
  }

  return (
    <div className="relative flex min-h-screen">
      {/* Left Side - Branding */}
      <div className="hidden flex-1 bg-gradient-to-br from-[#91C4D9] to-[#5b9ebd] lg:flex lg:flex-col lg:items-center lg:justify-center lg:p-12">
        <div className="max-w-md text-center">
          <div className="mb-8 flex justify-center">
            <div className="relative h-20 w-20 overflow-hidden rounded-2xl bg-white/20 shadow-lg backdrop-blur-sm">
              <Image
                src="/images/logo.png"
                alt="Studo Guide"
                fill
                className="object-contain"
              />
            </div>
          </div>
          <h1 className="text-4xl font-bold text-white">Join Studo Guide</h1>
          <p className="mt-3 text-lg text-white/80">Start Your Academic Journey Today</p>
          <p className="mt-6 text-sm leading-relaxed text-white/70">
            Create your free account and get access to AI career coaching, academic tracking,
            bursary discovery, and much more.
          </p>

          {/* Benefits */}
          <div className="mt-10 space-y-3 text-left">
            {[
              'AI-powered career guidance',
              'Track academic results',
              'Discover bursaries',
              'Connect with tutors',
            ].map((benefit) => (
              <div key={benefit} className="flex items-center gap-3 rounded-lg bg-white/10 p-3 backdrop-blur-sm">
                <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-white/20">
                  <svg className="h-3 w-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                  </svg>
                </div>
                <span className="text-sm text-white/90">{benefit}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Right Side - Registration Form */}
      <div className="flex-1 overflow-y-auto bg-[#f5f6fa] px-4 py-8 lg:max-w-[640px]">
        <div className="mx-auto w-full max-w-lg">
          {/* Mobile Logo */}
          <div className="mb-6 flex justify-center lg:hidden">
            <div className="flex items-center gap-3">
              <div className="relative h-10 w-10 overflow-hidden rounded-lg bg-gradient-to-br from-[#91C4D9] to-[#5b9ebd]">
                <Image
                  src="/images/logo.png"
                  alt="Studo Guide"
                  fill
                  className="object-contain"
                />
              </div>
              <h1 className="text-xl font-bold bg-gradient-to-r from-[#91C4D9] to-[#5b9ebd] bg-clip-text text-transparent">
                Studo Guide
              </h1>
            </div>
          </div>

          <Card className="border-0 shadow-lg">
            <CardHeader className="space-y-1 text-center pb-4">
              <CardTitle className="text-2xl font-bold text-[#2c3e50]">
                Create Your Account
              </CardTitle>
              <CardDescription className="text-gray-500">
                Fill in your details to get started
              </CardDescription>
            </CardHeader>
            <CardContent>
              {/* Assessment Results Notice */}
              {assessmentResult && (
                <div className="mb-4 flex items-start gap-3 rounded-lg border border-green-200 bg-green-50 p-3">
                  <GraduationCap className="mt-0.5 h-5 w-5 flex-shrink-0 text-green-600" />
                  <div>
                    <p className="text-sm font-medium text-green-800">Assessment Completed!</p>
                    <p className="text-xs text-green-600">Your results will be available in your dashboard after registration.</p>
                  </div>
                </div>
              )}

              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Personal Information */}
                <div>
                  <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-[#5b9ebd]">
                    Personal Information
                  </h3>
                  <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label htmlFor="firstName">First Name *</Label>
                      <Input
                        id="firstName"
                        placeholder="John"
                        value={form.firstName}
                        onChange={(e) => updateForm('firstName', e.target.value)}
                        required
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="lastName">Last Name *</Label>
                      <Input
                        id="lastName"
                        placeholder="Doe"
                        value={form.lastName}
                        onChange={(e) => updateForm('lastName', e.target.value)}
                        required
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                  </div>
                  <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label htmlFor="regEmail">Email Address *</Label>
                      <Input
                        id="regEmail"
                        type="email"
                        placeholder="you@example.com"
                        value={form.email}
                        onChange={(e) => updateForm('email', e.target.value)}
                        required
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="phone">Phone Number *</Label>
                      <Input
                        id="phone"
                        type="tel"
                        placeholder="072 123 4567"
                        value={form.phone}
                        onChange={(e) => updateForm('phone', e.target.value)}
                        required
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                  </div>
                  <div className="mt-3 space-y-1.5">
                    <Label htmlFor="regPassword">Password *</Label>
                    <div className="relative">
                      <Input
                        id="regPassword"
                        type={showPassword ? 'text' : 'password'}
                        placeholder="Create a strong password"
                        value={form.password}
                        onChange={(e) => updateForm('password', e.target.value)}
                        required
                        className="h-10 border-gray-200 pr-10 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                      >
                        {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </button>
                    </div>
                  </div>
                </div>

                {/* Academic Details */}
                <div>
                  <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-[#5b9ebd]">
                    Academic Details
                  </h3>
                  <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label>Gender *</Label>
                      <Select value={form.gender} onValueChange={(v) => updateForm('gender', v)}>
                        <SelectTrigger className="h-10 w-full border-gray-200">
                          <SelectValue placeholder="Select gender" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="male">Male</SelectItem>
                          <SelectItem value="female">Female</SelectItem>
                          <SelectItem value="other">Other</SelectItem>
                          <SelectItem value="prefer-not">Prefer not to say</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="dob">Date of Birth *</Label>
                      <Input
                        id="dob"
                        type="date"
                        value={form.dateOfBirth}
                        onChange={(e) => updateForm('dateOfBirth', e.target.value)}
                        required
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                  </div>
                  <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label>Grade *</Label>
                      <Select value={form.grade} onValueChange={(v) => updateForm('grade', v)}>
                        <SelectTrigger className="h-10 w-full border-gray-200">
                          <SelectValue placeholder="Select grade" />
                        </SelectTrigger>
                        <SelectContent>
                          {BRAND.grades.map((g) => (
                            <SelectItem key={g} value={String(g)}>
                              {gradeLabels[g]}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1.5">
                      <Label>Province *</Label>
                      <Select value={form.province} onValueChange={(v) => updateForm('province', v)}>
                        <SelectTrigger className="h-10 w-full border-gray-200">
                          <SelectValue placeholder="Select province" />
                        </SelectTrigger>
                        <SelectContent>
                          {BRAND.provinces.map((province) => (
                            <SelectItem key={province} value={province}>
                              {province}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label htmlFor="city">City *</Label>
                      <Input
                        id="city"
                        placeholder="e.g. Johannesburg"
                        value={form.city}
                        onChange={(e) => updateForm('city', e.target.value)}
                        required
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="suburb">Suburb</Label>
                      <Input
                        id="suburb"
                        placeholder="e.g. Sandton"
                        value={form.suburb}
                        onChange={(e) => updateForm('suburb', e.target.value)}
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                  </div>
                  <div className="mt-3 space-y-1.5">
                    <Label htmlFor="schoolName">School Name *</Label>
                    <Input
                      id="schoolName"
                      placeholder="Enter your school name"
                      value={form.schoolName}
                      onChange={(e) => updateForm('schoolName', e.target.value)}
                      required
                      className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                    />
                  </div>
                </div>

                {/* Subjects */}
                <div>
                  <h3 className="mb-1 text-sm font-semibold uppercase tracking-wider text-[#5b9ebd]">
                    Subjects You Need Help With
                  </h3>
                  <p className="mb-3 text-xs text-gray-400">Select all that apply</p>
                  <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                    {BRAND.saSubjects.map((subject) => {
                      const isChecked = selectedSubjects.includes(subject)
                      return (
                        <label
                          key={subject}
                          className={`flex cursor-pointer items-center gap-2 rounded-lg border p-2 text-xs transition-all ${
                            isChecked
                              ? 'border-[#91C4D9] bg-[#91C4D9]/10 text-[#2c3e50]'
                              : 'border-gray-200 hover:border-gray-300 text-gray-600'
                          }`}
                        >
                          <Checkbox
                            checked={isChecked}
                            onCheckedChange={() => toggleSubject(subject)}
                            className="data-[state=checked]:bg-[#5b9ebd] data-[state=checked]:border-[#5b9ebd]"
                          />
                          <span className="truncate">{subject}</span>
                        </label>
                      )
                    })}
                  </div>
                </div>

                {/* Parent / Guardian (Optional) */}
                <div>
                  <h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-[#5b9ebd]">
                    Parent / Guardian <span className="text-xs font-normal text-gray-400">(Optional)</span>
                  </h3>
                  <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="space-y-1.5">
                      <Label htmlFor="parentEmail">Parent Email</Label>
                      <Input
                        id="parentEmail"
                        type="email"
                        placeholder="parent@email.com"
                        value={form.parentEmail}
                        onChange={(e) => updateForm('parentEmail', e.target.value)}
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="parentPhone">Parent Phone</Label>
                      <Input
                        id="parentPhone"
                        type="tel"
                        placeholder="072 123 4567"
                        value={form.parentPhone}
                        onChange={(e) => updateForm('parentPhone', e.target.value)}
                        className="h-10 border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
                      />
                    </div>
                  </div>
                </div>

                {/* How Heard About Us */}
                <div className="space-y-1.5">
                  <Label>How did you hear about us?</Label>
                  <Select value={form.howHeard} onValueChange={(v) => updateForm('howHeard', v)}>
                    <SelectTrigger className="h-10 w-full border-gray-200">
                      <SelectValue placeholder="Select an option" />
                    </SelectTrigger>
                    <SelectContent>
                      {howHeardOptions.map((option) => (
                        <SelectItem key={option} value={option}>
                          {option}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Submit */}
                <Button
                  type="submit"
                  disabled={loading}
                  className="h-11 w-full bg-gradient-to-r from-[#91C4D9] to-[#5b9ebd] text-white hover:opacity-90 font-semibold shadow-md"
                >
                  {loading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Creating Account...
                    </>
                  ) : (
                    'Create Account'
                  )}
                </Button>
              </form>

              {/* Login Link */}
              <p className="mt-4 text-center text-sm text-gray-500">
                Already have an account?{' '}
                <Link
                  href="/login"
                  className="font-semibold text-[#5b9ebd] hover:text-[#91C4D9] hover:underline"
                >
                  Sign In
                </Link>
              </p>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}

export default function RegisterPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-[#f5f6fa]"><div className="animate-spin w-8 h-8 border-3 border-[#91C4D9] border-t-transparent rounded-full" /></div>}>
      <RegisterForm />
    </Suspense>
  )
}
