import React, { useState, useEffect, useRef } from 'react';
import {
  User,
  Compass,
  Building,
  Users,
  ArrowUpRight,
  Loader2,
  CheckCircle2,
  AlertTriangle,
  MessageCircle,
  Calculator,
  Percent,
} from 'lucide-react';
import { motion } from 'motion/react';
import { Container, Pill } from '../components/Ui';
import { BRAND } from '../components/Brand';
import { COURSES, findCourseBySlug, ZiteCourse } from '../data/courses';
import { WORKSHOP_TOPICS } from './OrganisationsPage';
import { getPricingForCourse, formatMoney, Currency } from '../data/pricing';

export type EnquiryMode = 'learner' | 'guidance' | 'corporate' | 'partnership';

const ENQUIRY_TABS: { id: EnquiryMode; label: string; Icon: React.ComponentType<{ className?: string }> }[] = [
  { id: 'learner', label: 'Learner enrolment', Icon: User },
  { id: 'guidance', label: 'Course guidance', Icon: Compass },
  { id: 'corporate', label: 'Corporate training', Icon: Building },
  { id: 'partnership', label: 'Partnership', Icon: Users },
];

const FIELD_LABELS: Record<string, string> = {
  name: 'Full name',
  email: 'Email',
  phone: 'Phone/WhatsApp number',
  course: 'Course',
  organisation: 'Organisation',
  message: 'Message',
};

interface ContactPageProps {
  onNavigate: (path: string) => void;
  initialMode?: EnquiryMode;
  initialCourse?: string;
  initialTopic?: string;
  initialPlan?: string;
  initialCurrency?: string;
}

export function ContactPage({
  onNavigate,
  initialMode = 'learner',
  initialCourse = '',
  initialTopic = '',
  initialPlan = '',
  initialCurrency = 'KES',
}: ContactPageProps) {
  const [mode, setMode] = useState<EnquiryMode>(initialMode);
  const [name, setName] = useState('');
  const [method, setMethod] = useState<'email' | 'phone' | 'whatsapp'>('email');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [course, setCourse] = useState(initialCourse);
  const [plan, setPlan] = useState(initialPlan);
  const [currency, setCurrency] = useState<Currency>((initialCurrency as Currency) || 'KES');
  const [organisation, setOrganisation] = useState('');
  const [topic, setTopic] = useState(initialTopic);
  const [teamSize, setTeamSize] = useState('');
  const [message, setMessage] = useState('');

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [status, setStatus] = useState<'idle' | 'sending' | 'done'>('idle');
  const [serverError, setServerError] = useState<string | null>(null);
  const [enquiryRef, setEnquiryRef] = useState<string>('');
  const [honeypot, setHoneypot] = useState('');
  const errorRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (initialMode) setMode(initialMode);
    if (initialCourse) setCourse(initialCourse);
    if (initialTopic) setTopic(initialTopic);
    if (initialPlan) setPlan(initialPlan);
    if (initialCurrency) setCurrency((initialCurrency as Currency) || 'KES');
  }, [initialMode, initialCourse, initialTopic, initialPlan, initialCurrency]);

  const selectedCourseObj = course ? findCourseBySlug(course) : undefined;
  const pricing = selectedCourseObj ? getPricingForCourse(selectedCourseObj.slug) : undefined;

  const validate = () => {
    const errs: Record<string, string> = {};
    if (!name.trim()) errs.name = 'Please provide your full name.';

    if (method === 'email') {
      if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
        errs.email = 'Please provide a valid email address.';
      }
    } else {
      if (!phone.trim() || phone.trim().length < 7) {
        errs.phone = 'Please provide a valid phone or WhatsApp number.';
      }
    }

    if (mode === 'learner' && !course) {
      errs.course = 'Please select a programme from the catalogue.';
    }

    if ((mode === 'corporate' || mode === 'partnership') && !organisation.trim()) {
      errs.organisation = 'Please provide your organisation name.';
    }

    setErrors(errs);
    if (Object.keys(errs).length > 0) {
      setTimeout(() => errorRef.current?.focus(), 50);
      return false;
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setServerError(null);
    if (!validate()) return;

    setStatus('sending');

    try {
      const response = await fetch('/api/enquiries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fullName: name.trim(),
          email: email.trim(),
          phone: phone.trim() || undefined,
          contactMethod: method,
          mode,
          courseSlug: selectedCourseObj?.slug,
          courseTitle: selectedCourseObj?.title,
          organisation: organisation.trim() || undefined,
          topic: topic.trim() || undefined,
          teamSize: teamSize.trim() || undefined,
          timeframe: 'Upcoming intake',
          currency,
          plan: plan || undefined,
          message: message.trim() || undefined,
          sourcePage: '/contact',
          honeypot: honeypot.trim() || undefined,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        setServerError(data.error || 'Failed to submit enquiry. Please try again.');
        setStatus('idle');
        return;
      }

      setEnquiryRef(data.enquiryRef || `ENQ-${Date.now().toString().slice(-6)}`);
      setStatus('done');
    } catch (err: any) {
      console.error('Contact submission error:', err);
      setServerError('A network error occurred. Please verify your connection and try again.');
      setStatus('idle');
    }
  };

  const handleReset = () => {
    setStatus('idle');
    setName('');
    setEmail('');
    setPhone('');
    setMessage('');
    setOrganisation('');
    setTeamSize('');
    setErrors({});
    setServerError(null);
    setEnquiryRef('');
  };

  return (
    <div className="min-h-screen pb-16">
      <Container className="pt-6 grid gap-6 lg:grid-cols-12">
        {/* Left Column: Dark Panel */}
        <div className="relative isolate overflow-hidden lg:col-span-5 bg-primary text-primary-foreground rounded-3xl p-7 md:p-9 flex flex-col justify-between shadow-md">
          <img
            src="https://images.fillout.com/902438/vk44zcsdgn/generated-images/tRvSZ66Xk5GsWAJgT2tmTb/img_AAHfJ7TiUYZ8kYxc.jpg"
            alt=""
            className="absolute -z-10 inset-x-0 top-0 h-56 w-full object-cover opacity-35"
          />
          <div className="absolute -z-10 inset-x-0 top-0 h-56 bg-gradient-to-b from-transparent to-primary" />
          <div className="h-28" aria-hidden="true" />

          <div>
            <h1 className="relative text-4xl md:text-5xl font-bold leading-[0.95] tracking-tight">
              Tell us what you <span className="serif-accent text-accent">want to learn.</span>
            </h1>

            {/* Mode Tabs */}
            <div className="mt-8 grid gap-2" role="tablist" aria-label="Enquiry type">
              {ENQUIRY_TABS.map(({ id: tabId, label, Icon }) => {
                const isSelected = mode === tabId;
                return (
                  <button
                    key={tabId}
                    role="tab"
                    aria-selected={isSelected}
                    onClick={() => {
                      setMode(tabId);
                      setErrors({});
                    }}
                    className={`rounded-2xl p-4 flex items-center gap-3 text-sm text-left transition cursor-pointer ${
                      isSelected
                        ? 'bg-accent text-accent-foreground font-semibold shadow-xs'
                        : 'border border-primary-foreground/30 hover:bg-primary-foreground/10 text-primary-foreground'
                    }`}
                  >
                    <Icon className="h-5 w-5 shrink-0" />
                    <span>{label}</span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Bottom Direct Contacts */}
          <div className="mt-auto pt-8 text-sm space-y-2 border-t border-white/10">
            <a href={`mailto:${BRAND.email}`} className="block hover:text-accent transition-colors">
              {BRAND.email}
            </a>
            <a href={BRAND.phoneHref} className="block hover:text-accent transition-colors">
              {BRAND.phone}
            </a>
            <a
              href={BRAND.whatsapp}
              target="_blank"
              rel="noreferrer"
              className="flex items-center gap-1.5 hover:text-accent transition-colors text-accent pt-1"
            >
              <span>Continue to WhatsApp</span>
              <ArrowUpRight className="h-4 w-4" />
            </a>
            <p className="opacity-60 text-xs pt-1">{BRAND.location}</p>
          </div>
        </div>

        {/* Right Column: Form Panel */}
        <div className="lg:col-span-7 bg-card border border-border rounded-3xl p-7 md:p-9 shadow-xs">
          {/* Prototype disclosure badge */}
          <div className="bg-primary/10 text-primary border border-primary/20 rounded-full px-4 py-1.5 text-xs font-semibold w-fit mb-6">
            Admissions Desk · Submissions recorded in durable database
          </div>

          {status === 'done' ? (
            /* Done State with Real Confirmation */
            <div className="mt-8 relative overflow-hidden rounded-3xl bg-secondary p-8" role="status">
              <svg
                viewBox="0 0 400 120"
                className="absolute inset-x-0 bottom-0 w-full h-24 pointer-events-none"
                aria-hidden="true"
              >
                <motion.path
                  d="M-10 120 C 100 70, 200 50, 410 0 L 410 40 C 220 80, 120 100, -10 150 Z"
                  fill="#D5E64D"
                  initial={{ x: -400 }}
                  animate={{ x: 0 }}
                  transition={{ duration: 0.9, ease: [0.2, 0.8, 0.2, 1] }}
                />
              </svg>

              <div className="relative pb-6 space-y-4">
                <CheckCircle2 className="h-10 w-10 text-primary" />
                <div className="space-y-1">
                  <span className="text-xs font-mono font-bold uppercase tracking-wider text-teal bg-teal-soft px-3 py-1 rounded-full">
                    Reference: {enquiryRef}
                  </span>
                  <h2 className="text-3xl font-bold mt-3">
                    Thank you, {name.split(' ')[0] || 'there'}. <span className="serif-accent">Enquiry received.</span>
                  </h2>
                </div>
                <p className="text-muted-foreground text-sm max-w-md leading-relaxed">
                  Your enquiry has been successfully stored in the PANIA admissions register. An admissions advisor will review your requested track and respond through your chosen channel (<strong>{method.toUpperCase()}</strong>).
                </p>

                <div className="p-3.5 rounded-2xl bg-card border border-border text-xs text-muted-foreground space-y-1 max-w-md">
                  <p className="font-semibold text-foreground">Prototype Verification Notice:</p>
                  <p>
                    Record logged durably in <code>/data/enquiries.json</code> with rate limits and idempotency protection. Admissions customer desk inbox: <code>admissions@pania.co.ke</code>.
                  </p>
                </div>

                <div className="flex flex-wrap gap-3 pt-3">
                  {selectedCourseObj ? (
                    <Pill to={`/programmes/${selectedCourseObj.slug}`}>
                      Back to {selectedCourseObj.title}
                    </Pill>
                  ) : (
                    <Pill to="/programmes">Explore programmes</Pill>
                  )}
                  <button
                    onClick={handleReset}
                    className="rounded-full px-5 py-3 text-sm font-medium border border-border bg-card hover:bg-secondary transition cursor-pointer"
                  >
                    Submit another enquiry
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate className="space-y-5">
              {/* Bot trap honeypot */}
              <input
                type="text"
                name="organization_honeypot"
                value={honeypot}
                onChange={(e) => setHoneypot(e.target.value)}
                className="hidden"
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
              />

              {/* Server Error Alert */}
              {serverError && (
                <div role="alert" className="border border-destructive/40 bg-destructive/10 text-destructive rounded-2xl p-4 text-xs font-semibold">
                  {serverError}
                </div>
              )}

              {/* Errors Banner */}
              {Object.keys(errors).length > 0 && (
                <div
                  ref={errorRef}
                  tabIndex={-1}
                  role="alert"
                  className="border-2 border-destructive/60 bg-destructive/5 rounded-2xl p-4 text-sm outline-none"
                >
                  <p className="font-semibold flex items-center gap-2 text-destructive">
                    <AlertTriangle className="h-4 w-4" />
                    <span>Please fix {Object.keys(errors).length} issue{Object.keys(errors).length > 1 ? 's' : ''}:</span>
                  </p>
                  <ul className="mt-2 list-disc pl-6 space-y-0.5 text-xs text-foreground">
                    {Object.entries(errors).map(([key, msg]) => (
                      <li key={key}>
                        <b>{FIELD_LABELS[key] || key}:</b> {msg}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Selected Payment Plan Banner from Tuition Calculator */}
              {plan && selectedCourseObj && pricing && (
                <div className="p-4 rounded-2xl bg-secondary/70 border border-border space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold text-foreground flex items-center gap-1.5">
                      <Calculator className="w-4 h-4 text-primary" />
                      <span>Selected Payment Plan</span>
                    </span>
                    <span className="text-[11px] font-bold px-2.5 py-0.5 rounded-full bg-accent text-accent-foreground">
                      {plan === 'full'
                        ? '10% Early Bird Full'
                        : plan === 'two-part'
                        ? '2-Part Milestone (50%/50%)'
                        : plan === 'sponsorship'
                        ? 'Community Financial Aid'
                        : '3-Part Monthly'}
                    </span>
                  </div>
                  <div className="flex items-baseline justify-between text-foreground">
                    <p className="text-sm font-bold">{selectedCourseObj.title}</p>
                    <p className="text-sm font-extrabold text-primary">
                      {currency === 'KES'
                        ? formatMoney(Math.round(plan === 'full' ? pricing.baseKes * 0.9 : pricing.baseKes), 'KES')
                        : formatMoney(Math.round(plan === 'full' ? pricing.baseUsd * 0.9 : pricing.baseUsd), 'USD')}
                    </p>
                  </div>
                  <p className="text-[11px] text-muted-foreground">
                    Your seat enquiry will be reserved under this fee structure with zero immediate commitment.
                  </p>
                </div>
              )}

              {/* Course Selection (for learner or guidance) */}
              {mode === 'learner' && (
                <div>
                  <label htmlFor="f-course" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                    Course <span className="text-destructive">*</span>
                  </label>
                  <select
                    id="f-course"
                    value={course}
                    onChange={(e) => setCourse(e.target.value)}
                    className={`w-full bg-input border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary ${
                      errors.course ? 'border-destructive' : 'border-border'
                    }`}
                  >
                    <option value="">Choose a course</option>
                    {COURSES.map((c) => (
                      <option key={c.slug} value={c.slug}>
                        {c.title} ({c.provider})
                      </option>
                    ))}
                  </select>
                  {errors.course && <p className="text-destructive text-xs mt-1">{errors.course}</p>}
                </div>
              )}

              {mode === 'guidance' && (
                <div>
                  <label htmlFor="f-course-guidance" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                    Course of interest (optional)
                  </label>
                  <select
                    id="f-course-guidance"
                    value={course}
                    onChange={(e) => setCourse(e.target.value)}
                    className="w-full bg-input border border-border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary"
                  >
                    <option value="">Not sure yet — help me choose</option>
                    {COURSES.map((c) => (
                      <option key={c.slug} value={c.slug}>
                        {c.title} ({c.provider})
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {mode === 'corporate' && (
                <div className="grid gap-4 sm:grid-cols-2">
                  <div>
                    <label htmlFor="f-topic" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                      AWS Workshop (optional)
                    </label>
                    <select
                      id="f-topic"
                      value={topic}
                      onChange={(e) => setTopic(e.target.value)}
                      className="w-full bg-input border border-border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary"
                    >
                      <option value="">Choose AWS Workshop topic</option>
                      {WORKSHOP_TOPICS.map((t) => (
                        <option key={t.id} value={t.id}>
                          {t.id}: {t.summary}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label htmlFor="f-size" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                      Approximate Team Size
                    </label>
                    <input
                      id="f-size"
                      type="text"
                      placeholder="e.g. 5–15 participants"
                      value={teamSize}
                      onChange={(e) => setTeamSize(e.target.value)}
                      className="w-full bg-input border border-border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary"
                    />
                  </div>
                </div>
              )}

              {/* Organisation Field */}
              {(mode === 'corporate' || mode === 'partnership') && (
                <div>
                  <label htmlFor="f-org" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                    Organisation / Institution <span className="text-destructive">*</span>
                  </label>
                  <input
                    id="f-org"
                    type="text"
                    value={organisation}
                    onChange={(e) => setOrganisation(e.target.value)}
                    placeholder="e.g. Acme Corporation"
                    className={`w-full bg-input border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary ${
                      errors.organisation ? 'border-destructive' : 'border-border'
                    }`}
                  />
                  {errors.organisation && <p className="text-destructive text-xs mt-1">{errors.organisation}</p>}
                </div>
              )}

              {/* Full Name */}
              <div>
                <label htmlFor="f-name" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                  Full name <span className="text-destructive">*</span>
                </label>
                <input
                  id="f-name"
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="e.g. Joy Muthoni"
                  className={`w-full bg-input border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary ${
                    errors.name ? 'border-destructive' : 'border-border'
                  }`}
                  autoComplete="name"
                />
                {errors.name && <p className="text-destructive text-xs mt-1">{errors.name}</p>}
              </div>

              {/* Contact Method Selector */}
              <fieldset>
                <legend className="text-xs font-semibold text-muted-foreground mb-1.5">
                  Preferred contact method
                </legend>
                <div className="flex flex-wrap gap-2">
                  {(['email', 'phone', 'whatsapp'] as const).map((m) => (
                    <button
                      key={m}
                      type="button"
                      aria-pressed={method === m}
                      onClick={() => setMethod(m)}
                      className={`rounded-full px-5 py-2.5 min-h-[44px] text-xs font-semibold border transition cursor-pointer flex items-center justify-center ${
                        method === m
                          ? 'bg-primary text-primary-foreground border-primary shadow-2xs'
                          : 'border-border hover:bg-secondary text-foreground'
                      }`}
                    >
                      {m === 'whatsapp' ? 'WhatsApp' : m === 'phone' ? 'Phone' : 'Email'}
                    </button>
                  ))}
                </div>
              </fieldset>

              {/* Dynamic Email / Phone Field */}
              {method === 'email' ? (
                <div>
                  <label htmlFor="f-email" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                    Email address <span className="text-destructive">*</span>
                  </label>
                  <input
                    id="f-email"
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="name@example.com"
                    className={`w-full bg-input border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary ${
                      errors.email ? 'border-destructive' : 'border-border'
                    }`}
                    autoComplete="email"
                  />
                  {errors.email && <p className="text-destructive text-xs mt-1">{errors.email}</p>}
                </div>
              ) : (
                <div>
                  <label htmlFor="f-phone" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                    {method === 'whatsapp' ? 'WhatsApp number' : 'Phone number'} <span className="text-destructive">*</span>
                  </label>
                  <input
                    id="f-phone"
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="+254 7… (international format)"
                    className={`w-full bg-input border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary ${
                      errors.phone ? 'border-destructive' : 'border-border'
                    }`}
                    autoComplete="tel"
                  />
                  {errors.phone && <p className="text-destructive text-xs mt-1">{errors.phone}</p>}
                </div>
              )}

              {/* Message */}
              <div>
                <label htmlFor="f-message" className="text-xs font-semibold text-muted-foreground block mb-1.5">
                  Message or questions (optional)
                </label>
                <textarea
                  id="f-message"
                  rows={5}
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  placeholder="Share any questions about schedules, background or team goals..."
                  className="w-full min-h-[130px] bg-input border border-border rounded-xl px-4 py-3 text-base sm:text-sm outline-none focus:ring-2 focus:ring-primary leading-relaxed resize-y"
                />
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={status === 'sending'}
                className="bg-primary text-primary-foreground hover:opacity-90 rounded-full px-8 py-3.5 text-sm font-bold inline-flex items-center gap-2 cursor-pointer shadow-xs disabled:opacity-70"
              >
                {status === 'sending' ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span>Sending…</span>
                  </>
                ) : (
                  <>
                    <span>Send enquiry</span>
                    <ArrowUpRight className="h-4 w-4" />
                  </>
                )}
              </button>
            </form>
          )}
        </div>
      </Container>
    </div>
  );
}
