'use client'

import { useState, useMemo } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  CreditCard,
  FileText,
  Download,
  Award,
  Loader2,
  CheckCircle2,
  Users,
} from 'lucide-react'
import {
  CourseDetail,
  calculateFees,
  formatPrice,
  generateEnrollmentRef,
  generateCertificateNumber,
  getCourseStartDate,
} from '@/lib/courses'
import { downloadInvoice, downloadCertificate, type EnrollmentData } from '@/lib/documents'
import { siteConfig } from '@/lib/site-config'

interface CourseEnrollmentProps {
  course: CourseDetail
}

type Step = 'form' | 'processing' | 'complete'

export function CourseEnrollment({ course }: CourseEnrollmentProps) {
  const [step, setStep] = useState<Step>('form')
  const [paymentMethod, setPaymentMethod] = useState<'invoice' | 'online'>('online')
  const [participants, setParticipants] = useState(1)
  const [form, setForm] = useState({
    firstName: '',
    lastName: '',
    email: '',
    organisation: '',
    phone: '',
  })
  const [enrollment, setEnrollment] = useState<(EnrollmentData & { certificateNumber: string }) | null>(null)

  const fees = useMemo(() => calculateFees(course.price, participants), [course.price, participants])
  const courseDate = getCourseStartDate(course.scheduleOffset)
  const isValid = form.firstName && form.lastName && form.email && form.organisation

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!isValid) return

    setStep('processing')

    setTimeout(() => {
      const ref = generateEnrollmentRef()
      const certNum = generateCertificateNumber()
      const data: EnrollmentData & { certificateNumber: string } = {
        ref,
        certificateNumber: certNum,
        participantName: `${form.firstName} ${form.lastName}`,
        email: form.email,
        organisation: form.organisation,
        courseTitle: course.title,
        courseDate,
        paymentMethod,
        fees,
        paidAt: paymentMethod === 'online' ? new Date().toLocaleString('en-GB') : undefined,
      }
      setEnrollment(data)
      setStep('complete')

      if (paymentMethod === 'invoice') {
        downloadInvoice(data)
      }
    }, paymentMethod === 'online' ? 2500 : 800)
  }

  if (step === 'processing') {
    return (
      <Card className="border-border/50">
        <CardContent className="py-16 text-center">
          <Loader2 className="w-10 h-10 text-primary animate-spin mx-auto mb-4" />
          <p className="font-semibold text-lg">
            {paymentMethod === 'online' ? 'Processing payment...' : 'Generating invoice...'}
          </p>
          <p className="text-sm text-muted-foreground mt-2">Please wait a moment</p>
        </CardContent>
      </Card>
    )
  }

  if (step === 'complete' && enrollment) {
    return (
      <Card className="border-green-200 bg-green-50/30">
        <CardContent className="py-8 space-y-6">
          <div className="text-center">
            <CheckCircle2 className="w-14 h-14 text-green-600 mx-auto mb-4" />
            <h3 className="text-xl font-bold text-foreground">Enrollment Confirmed!</h3>
            <p className="text-sm text-muted-foreground mt-2">Reference: <strong>{enrollment.ref}</strong></p>
          </div>

          <div className="bg-white rounded-xl border border-border/50 p-5 space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-muted-foreground">Course</span><span className="font-medium text-right max-w-[60%]">{course.title}</span></div>
            <div className="flex justify-between"><span className="text-muted-foreground">Date</span><span>{courseDate}</span></div>
            <div className="flex justify-between"><span className="text-muted-foreground">Participants</span><span>{participants}</span></div>
            <div className="flex justify-between font-bold text-primary text-base pt-2 border-t"><span>Total Paid</span><span>{enrollment.fees.formatted.total}</span></div>
          </div>

          <div className="grid sm:grid-cols-2 gap-3">
            <Button
              variant="outline"
              className="gap-2"
              onClick={() => downloadInvoice(enrollment)}
            >
              <FileText className="w-4 h-4" />
              Download Invoice
            </Button>
            <Button
              className="gap-2 bg-primary hover:bg-primary/90"
              onClick={() => downloadCertificate(enrollment)}
            >
              <Award className="w-4 h-4" />
              Download Certificate
            </Button>
          </div>

          <p className="text-xs text-muted-foreground text-center">
            A confirmation email will be sent to {enrollment.email}. Certificate is also available after course completion.
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="border-border/50 sticky top-24">
      <CardHeader className="border-b border-border/50 bg-muted/30">
        <CardTitle className="text-lg">Enrol Now</CardTitle>
        <p className="text-2xl font-bold text-primary">{formatPrice(course.price)} <span className="text-sm font-normal text-muted-foreground">/ person</span></p>
      </CardHeader>
      <CardContent className="pt-6">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium mb-1 block">First Name *</label>
              <input
                required
                value={form.firstName}
                onChange={(e) => setForm({ ...form, firstName: e.target.value })}
                className="w-full px-3 py-2 text-sm border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/30"
              />
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Last Name *</label>
              <input
                required
                value={form.lastName}
                onChange={(e) => setForm({ ...form, lastName: e.target.value })}
                className="w-full px-3 py-2 text-sm border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/30"
              />
            </div>
          </div>

          <div>
            <label className="text-xs font-medium mb-1 block">Email *</label>
            <input
              type="email"
              required
              value={form.email}
              onChange={(e) => setForm({ ...form, email: e.target.value })}
              className="w-full px-3 py-2 text-sm border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>

          <div>
            <label className="text-xs font-medium mb-1 block">Organisation *</label>
            <input
              required
              value={form.organisation}
              onChange={(e) => setForm({ ...form, organisation: e.target.value })}
              className="w-full px-3 py-2 text-sm border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>

          <div>
            <label className="text-xs font-medium mb-1 block">Phone</label>
            <input
              type="tel"
              value={form.phone}
              onChange={(e) => setForm({ ...form, phone: e.target.value })}
              className="w-full px-3 py-2 text-sm border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>

          <div>
            <label className="text-xs font-medium mb-1 flex items-center gap-1">
              <Users className="w-3.5 h-3.5" /> Participants
            </label>
            <select
              value={participants}
              onChange={(e) => setParticipants(Number(e.target.value))}
              className="w-full px-3 py-2 text-sm border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/30"
            >
              {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((n) => (
                <option key={n} value={n}>{n} participant{n > 1 ? 's' : ''}</option>
              ))}
            </select>
          </div>

          {/* Auto-calculated fees */}
          <div className="bg-muted/50 rounded-xl p-4 space-y-2 text-sm border border-border/50">
            <p className="font-semibold text-xs uppercase tracking-wider text-muted-foreground mb-2">Fee Summary (auto-calculated)</p>
            <div className="flex justify-between"><span>Course fee × {participants}</span><span>{fees.formatted.subtotal}</span></div>
            <div className="flex justify-between"><span>VAT ({siteConfig.vatRate * 100}%)</span><span>{fees.formatted.vat}</span></div>
            <div className="flex justify-between font-bold text-primary text-base pt-2 border-t border-border/50">
              <span>Total Fees</span><span>{fees.formatted.total}</span>
            </div>
          </div>

          {/* Payment method */}
          <div>
            <p className="text-xs font-medium mb-2">Payment Method *</p>
            <div className="grid grid-cols-2 gap-2">
              <button
                type="button"
                onClick={() => setPaymentMethod('online')}
                className={`flex flex-col items-center gap-1.5 p-3 rounded-xl border text-xs font-medium transition-all ${
                  paymentMethod === 'online'
                    ? 'border-primary bg-primary/5 text-primary ring-2 ring-primary/20'
                    : 'border-border hover:border-primary/30'
                }`}
              >
                <CreditCard className="w-5 h-5" />
                Online Payment
              </button>
              <button
                type="button"
                onClick={() => setPaymentMethod('invoice')}
                className={`flex flex-col items-center gap-1.5 p-3 rounded-xl border text-xs font-medium transition-all ${
                  paymentMethod === 'invoice'
                    ? 'border-primary bg-primary/5 text-primary ring-2 ring-primary/20'
                    : 'border-border hover:border-primary/30'
                }`}
              >
                <FileText className="w-5 h-5" />
                Invoice
              </button>
            </div>
          </div>

          {paymentMethod === 'online' && (
            <div className="space-y-3 p-4 border border-border/50 rounded-xl bg-background">
              <p className="text-xs font-medium">Card Details</p>
              <input placeholder="Card number" className="w-full px-3 py-2 text-sm border border-input rounded-lg" defaultValue="4242 4242 4242 4242" readOnly />
              <div className="grid grid-cols-2 gap-2">
                <input placeholder="MM/YY" className="px-3 py-2 text-sm border border-input rounded-lg" defaultValue="12/28" readOnly />
                <input placeholder="CVC" className="px-3 py-2 text-sm border border-input rounded-lg" defaultValue="123" readOnly />
              </div>
              <Badge variant="outline" className="text-xs">Secure demo payment — no real charge</Badge>
            </div>
          )}

          <Button
            type="submit"
            disabled={!isValid}
            className="w-full bg-primary hover:bg-primary/90 font-semibold h-11 gap-2"
          >
            {paymentMethod === 'online' ? (
              <><CreditCard className="w-4 h-4" /> Pay {fees.formatted.total}</>
            ) : (
              <><Download className="w-4 h-4" /> Request Invoice — {fees.formatted.total}</>
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}
