'use client';

import { useState, useEffect, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { ArrowLeft, Plus, Trash2, Send, Loader2, CheckCircle, AlertCircle } from 'lucide-react';
import Link from 'next/link';
import Header from '@/components/ui/header';
import Footer from '@/components/ui/footer';

function IntakeFormContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const sessionId = searchParams.get('session_id');

  const [verified, setVerified] = useState(false);
  const [verifying, setVerifying] = useState(true);
  const [verifyError, setVerifyError] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState('');

  // Form state
  const [title, setTitle] = useState('');
  const [clientName, setClientName] = useState('');
  const [clientEmail, setClientEmail] = useState('');
  const [clientCompany, setClientCompany] = useState('');
  const [businessDomain, setBusinessDomain] = useState('');
  const [problemStatement, setProblemStatement] = useState('');
  const [budget, setBudget] = useState('');
  const [timeline, setTimeline] = useState('');
  const [targetUsers, setTargetUsers] = useState<string[]>(['']);
  const [coreWorkflows, setCoreWorkflows] = useState<string[]>(['']);
  const [constraints, setConstraints] = useState<string[]>(['']);
  const [integrations, setIntegrations] = useState<string[]>(['']);
  const [notes, setNotes] = useState('');

  // Verify payment
  useEffect(() => {
    if (!sessionId) {
      setVerifyError('No payment session found. Please complete payment first.');
      setVerifying(false);
      return;
    }
    const verify = async () => {
      try {
        const res = await fetch(`/api/services/ai-scope/verify?session_id=${sessionId}`);
        const data = await res.json();
        if (data.verified) {
          setVerified(true);
          if (data.customerEmail) setClientEmail(data.customerEmail);
          if (data.customerName) setClientName(data.customerName);
        } else {
          setVerifyError(data.error || 'Payment could not be verified.');
        }
      } catch {
        setVerifyError('Failed to verify payment.');
      }
      setVerifying(false);
    };
    verify();
  }, [sessionId]);

  const addItem = (setter: React.Dispatch<React.SetStateAction<string[]>>) => setter(prev => [...prev, '']);
  const updateItem = (setter: React.Dispatch<React.SetStateAction<string[]>>, idx: number, val: string) => setter(prev => prev.map((v, i) => i === idx ? val : v));
  const removeItem = (setter: React.Dispatch<React.SetStateAction<string[]>>, idx: number) => setter(prev => prev.filter((_, i) => i !== idx));

  const handleSubmit = async () => {
    if (!title || !businessDomain || !problemStatement || !clientEmail) {
      setError('Project title, business domain, problem statement, and email are required.');
      return;
    }
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch('/api/services/ai-scope/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sessionId,
          title, clientName, clientEmail, clientCompany, businessDomain,
          problemStatement, budget, timeline, notes,
          targetUsers: targetUsers.filter(Boolean),
          coreWorkflows: coreWorkflows.filter(Boolean),
          constraints: constraints.filter(Boolean),
          integrations: integrations.filter(Boolean),
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Submission failed');
      setSubmitted(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
      setSubmitting(false);
    }
  };

  const inputClass = 'w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white placeholder-gray-500 focus:border-brand-deep focus:outline-none text-sm';
  const labelClass = 'block text-sm font-medium text-gray-300 mb-1';

  if (verifying) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] gap-4">
        <Loader2 className="w-8 h-8 animate-spin text-brand-deep" />
        <p className="text-gray-400">Verifying your payment...</p>
      </div>
    );
  }

  if (verifyError) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] gap-4 px-4">
        <AlertCircle className="w-12 h-12 text-red-400" />
        <p className="text-red-400 text-center">{verifyError}</p>
        <Link href="/services/ai-scope" className="text-brand-deep hover:underline">← Back to AI Scope</Link>
      </div>
    );
  }

  if (submitted) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] gap-6 px-4 text-center">
        <CheckCircle className="w-16 h-16 text-green-400" />
        <h2 className="text-3xl font-bold text-white">Project Submitted!</h2>
        <p className="text-gray-300 max-w-lg">
          The Hearth is now scoping your project. You&apos;ll receive your branded PDF scope
          document at <strong className="text-white">{clientEmail}</strong> within a few minutes.
        </p>
        <p className="text-gray-500 text-sm">Check your spam folder if you don&apos;t see it within 10 minutes.</p>
        <Link href="/" className="text-brand-deep hover:underline">← Back to Home</Link>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto space-y-8 px-4">
      <div>
        <h1 className="text-3xl font-bold text-white">Describe Your Project</h1>
        <p className="text-gray-400 mt-2">Payment confirmed! Now tell us about your project. The more detail you provide, the better your scope document will be.</p>
      </div>

      {error && <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">{error}</div>}

      {/* Client Info */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4">
        <h2 className="text-lg font-semibold text-white">Your Info</h2>
        <div className="grid md:grid-cols-2 gap-4">
          <div><label className={labelClass}>Your Name</label><input className={inputClass} value={clientName} onChange={e => setClientName(e.target.value)} placeholder="Full name" /></div>
          <div><label className={labelClass}>Email *</label><input className={inputClass} type="email" value={clientEmail} onChange={e => setClientEmail(e.target.value)} placeholder="Where to deliver your scope document" /></div>
          <div className="md:col-span-2"><label className={labelClass}>Company</label><input className={inputClass} value={clientCompany} onChange={e => setClientCompany(e.target.value)} placeholder="Company name (optional)" /></div>
        </div>
      </section>

      {/* Project Details */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4">
        <h2 className="text-lg font-semibold text-white">Project Details</h2>
        <div className="grid md:grid-cols-2 gap-4">
          <div><label className={labelClass}>Project Title *</label><input className={inputClass} value={title} onChange={e => setTitle(e.target.value)} placeholder="e.g., SchoolPlate - K-12 Nutrition Management" /></div>
          <div><label className={labelClass}>Business Domain *</label><input className={inputClass} value={businessDomain} onChange={e => setBusinessDomain(e.target.value)} placeholder="e.g., Education, Healthcare, Logistics" /></div>
        </div>
        <div><label className={labelClass}>Problem Statement *</label>
          <textarea className={`${inputClass} min-h-[120px]`} value={problemStatement} onChange={e => setProblemStatement(e.target.value)} placeholder="What problem does this software solve? Who uses it? What happens today without it? Be as detailed as possible — our AI uses this to build your scope." />
        </div>
        <div className="grid md:grid-cols-2 gap-4">
          <div><label className={labelClass}>Budget Range</label><input className={inputClass} value={budget} onChange={e => setBudget(e.target.value)} placeholder="e.g., $10,000-$50,000" /></div>
          <div><label className={labelClass}>Timeline</label><input className={inputClass} value={timeline} onChange={e => setTimeline(e.target.value)} placeholder="e.g., 3 months" /></div>
        </div>
      </section>

      {/* Scope */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-6">
        <h2 className="text-lg font-semibold text-white">Scope Details</h2>
        {[{ label: 'Target Users / Roles', items: targetUsers, setter: setTargetUsers, ph: 'e.g., Admin, Customer, Vendor' },
          { label: 'Core Workflows', items: coreWorkflows, setter: setCoreWorkflows, ph: 'e.g., Place order, Generate report, Send invoice' },
          { label: 'Constraints / Requirements', items: constraints, setter: setConstraints, ph: 'e.g., HIPAA compliant, mobile-first, offline support' },
          { label: 'External Integrations', items: integrations, setter: setIntegrations, ph: 'e.g., Stripe, QuickBooks, Salesforce' },
        ].map(({ label, items, setter, ph }) => (
          <div key={label}>
            <label className={labelClass}>{label}</label>
            {items.map((v, i) => (
              <div key={i} className="flex gap-2 mb-2">
                <input className={inputClass} value={v} onChange={e => updateItem(setter, i, e.target.value)} placeholder={ph} />
                {items.length > 1 && <button onClick={() => removeItem(setter, i)} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>}
              </div>
            ))}
            <button onClick={() => addItem(setter)} className="text-xs text-brand-deep hover:text-brand flex items-center gap-1"><Plus className="w-3 h-3" /> Add more</button>
          </div>
        ))}
      </section>

      {/* Notes */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6">
        <label className={labelClass}>Additional Notes</label>
        <textarea className={`${inputClass} min-h-[80px]`} value={notes} onChange={e => setNotes(e.target.value)} placeholder="Anything else we should know about your project..." />
      </section>

      {/* Submit */}
      <div className="flex justify-end gap-3 pb-12">
        <button onClick={handleSubmit} disabled={submitting}
          className="flex items-center gap-2 px-8 py-3 bg-brand-deep hover:bg-brand-deep/80 disabled:opacity-50 text-white rounded-lg font-semibold transition-colors">
          {submitting ? <Loader2 className="w-5 h-5 animate-spin" /> : <Send className="w-5 h-5" />}
          {submitting ? 'Submitting...' : 'Generate My Scope Document'}
        </button>
      </div>
    </div>
  );
}

export default function AIProjectScopeIntakePage() {
  return (
    <div className="min-h-screen bg-[#0C1222]">
      <Header />
      <main className="pt-24 pb-12">
        <Suspense fallback={
          <div className="flex items-center justify-center min-h-[60vh]">
            <Loader2 className="w-8 h-8 animate-spin text-brand-deep" />
          </div>
        }>
          <IntakeFormContent />
        </Suspense>
      </main>
      <Footer />
    </div>
  );
}
