'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Plus, Trash2, Save, Loader2 } from 'lucide-react';
import Link from 'next/link';
import { LANGUAGE_OPTIONS, DATABASE_OPTIONS } from '@/lib/dark-factory/types/generation-options';

interface EntityDraft {
  name: string;
  description: string;
  fields: { name: string; type: string }[];
  relationships: { target: string; type: string }[];
  isCore: boolean;
}

interface CriterionDraft {
  description: string;
  category: string;
  priority: string;
}

export default function NewIntakePage() {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  // Basic info
  const [title, setTitle] = useState('');
  const [clientName, setClientName] = useState('');
  const [clientCompany, setClientCompany] = useState('');
  const [businessDomain, setBusinessDomain] = useState('');
  const [problemStatement, setProblemStatement] = useState('');
  const [budget, setBudget] = useState('');
  const [timeline, setTimeline] = useState('');
  const [notes, setNotes] = useState('');

  // Stack
  const [targetLanguage, setTargetLanguage] = useState('typescript-react');
  const [targetDatabase, setTargetDatabase] = useState('postgresql');

  // Lists
  const [targetUsers, setTargetUsers] = useState<string[]>(['']);
  const [coreWorkflows, setCoreWorkflows] = useState<string[]>(['']);
  const [constraints, setConstraints] = useState<string[]>(['']);
  const [integrations, setIntegrations] = useState<string[]>(['']);

  // Entities
  const [entities, setEntities] = useState<EntityDraft[]>([]);
  const [acceptanceCriteria, setAcceptanceCriteria] = useState<CriterionDraft[]>([]);

  const addListItem = (setter: React.Dispatch<React.SetStateAction<string[]>>) => {
    setter(prev => [...prev, '']);
  };
  const updateListItem = (setter: React.Dispatch<React.SetStateAction<string[]>>, idx: number, val: string) => {
    setter(prev => prev.map((v, i) => i === idx ? val : v));
  };
  const removeListItem = (setter: React.Dispatch<React.SetStateAction<string[]>>, idx: number) => {
    setter(prev => prev.filter((_, i) => i !== idx));
  };

  const addEntity = () => {
    setEntities(prev => [...prev, { name: '', description: '', fields: [{ name: 'id', type: 'String' }], relationships: [], isCore: true }]);
  };

  const addCriterion = () => {
    setAcceptanceCriteria(prev => [...prev, { description: '', category: 'functional', priority: 'must' }]);
  };

  const handleSubmit = async () => {
    if (!title || !businessDomain || !problemStatement) {
      setError('Title, business domain, and problem statement are required.');
      return;
    }
    setSaving(true);
    setError('');

    try {
      const res = await fetch('/api/dark-factory/intake', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title, clientName, clientCompany, businessDomain, problemStatement,
          targetUsers: targetUsers.filter(Boolean),
          coreWorkflows: coreWorkflows.filter(Boolean),
          constraints: constraints.filter(Boolean),
          integrations: integrations.filter(Boolean),
          targetLanguage, targetDatabase, budget, timeline, notes,
          entities: entities.filter(e => e.name),
          acceptanceCriteria: acceptanceCriteria.filter(c => c.description),
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to create intake');
      router.push(`/dark-factory/app/intake/${data.intake.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
      setSaving(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';

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      <div className="flex items-center gap-3">
        <Link href="/dark-factory/app/intake" className="text-gray-400 hover:text-white transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">New Project Intake</h1>
          <p className="text-gray-400 text-sm">Define the project scope. This becomes the blueprint for everything that follows.</p>
        </div>
      </div>

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

      {/* Section 1: Client & Project */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4">
        <h2 className="text-lg font-semibold text-white">Client & Project</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><label className={labelClass}>Client Name</label><input className={inputClass} value={clientName} onChange={e => setClientName(e.target.value)} placeholder="Contact name" /></div>
          <div><label className={labelClass}>Client Company</label><input className={inputClass} value={clientCompany} onChange={e => setClientCompany(e.target.value)} placeholder="Company name" /></div>
        </div>
        <div><label className={labelClass}>Problem Statement *</label>
          <textarea className={`${inputClass} min-h-[100px]`} value={problemStatement} onChange={e => setProblemStatement(e.target.value)} placeholder="What problem does this software solve? Who uses it? What happens today without it?" />
        </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., $5,000-$10,000" /></div>
          <div><label className={labelClass}>Timeline</label><input className={inputClass} value={timeline} onChange={e => setTimeline(e.target.value)} placeholder="e.g., 2 weeks" /></div>
        </div>
      </section>

      {/* Section 2: Target Stack */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4">
        <h2 className="text-lg font-semibold text-white">Target Stack</h2>
        <div className="grid md:grid-cols-2 gap-4">
          <div>
            <label className={labelClass}>Language / Framework</label>
            <div className="grid grid-cols-1 gap-2">
              {LANGUAGE_OPTIONS.map(opt => (
                <button key={opt.id} onClick={() => setTargetLanguage(opt.id)}
                  className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-sm text-left transition-colors ${
                    targetLanguage === opt.id ? 'border-brand-deep bg-brand-deep/10 text-white' : 'border-slate-700 text-gray-400 hover:border-slate-600'
                  }`}>
                  <span>{opt.icon}</span> {opt.label}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className={labelClass}>Database</label>
            <div className="grid grid-cols-1 gap-2">
              {DATABASE_OPTIONS.map(opt => (
                <button key={opt.id} onClick={() => setTargetDatabase(opt.id)}
                  className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-sm text-left transition-colors ${
                    targetDatabase === opt.id ? 'border-brand-deep bg-brand-deep/10 text-white' : 'border-slate-700 text-gray-400 hover:border-slate-600'
                  }`}>
                  <span>{opt.icon}</span> {opt.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Section 3: Users, Workflows, Constraints, Integrations */}
      <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 Definition</h2>
        
        {/* Target Users */}
        <div>
          <label className={labelClass}>Target Users / Roles</label>
          {targetUsers.map((u, i) => (
            <div key={i} className="flex gap-2 mb-2">
              <input className={inputClass} value={u} onChange={e => updateListItem(setTargetUsers, i, e.target.value)} placeholder="e.g., Admin, Teacher, Student, Kitchen Staff" />
              {targetUsers.length > 1 && <button onClick={() => removeListItem(setTargetUsers, i)} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>}
            </div>
          ))}
          <button onClick={() => addListItem(setTargetUsers)} className="text-xs text-brand-deep hover:text-brand flex items-center gap-1"><Plus className="w-3 h-3" /> Add role</button>
        </div>

        {/* Core Workflows */}
        <div>
          <label className={labelClass}>Core Workflows</label>
          {coreWorkflows.map((w, i) => (
            <div key={i} className="flex gap-2 mb-2">
              <input className={inputClass} value={w} onChange={e => updateListItem(setCoreWorkflows, i, e.target.value)} placeholder="e.g., Place order, Manage menu, Check eligibility" />
              {coreWorkflows.length > 1 && <button onClick={() => removeListItem(setCoreWorkflows, i)} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>}
            </div>
          ))}
          <button onClick={() => addListItem(setCoreWorkflows)} className="text-xs text-brand-deep hover:text-brand flex items-center gap-1"><Plus className="w-3 h-3" /> Add workflow</button>
        </div>

        {/* Constraints */}
        <div>
          <label className={labelClass}>Constraints / Requirements</label>
          {constraints.map((c, i) => (
            <div key={i} className="flex gap-2 mb-2">
              <input className={inputClass} value={c} onChange={e => updateListItem(setConstraints, i, e.target.value)} placeholder="e.g., HIPAA compliant, must work offline, mobile-first" />
              {constraints.length > 1 && <button onClick={() => removeListItem(setConstraints, i)} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>}
            </div>
          ))}
          <button onClick={() => addListItem(setConstraints)} className="text-xs text-brand-deep hover:text-brand flex items-center gap-1"><Plus className="w-3 h-3" /> Add constraint</button>
        </div>

        {/* Integrations */}
        <div>
          <label className={labelClass}>External Integrations</label>
          {integrations.map((ig, i) => (
            <div key={i} className="flex gap-2 mb-2">
              <input className={inputClass} value={ig} onChange={e => updateListItem(setIntegrations, i, e.target.value)} placeholder="e.g., Stripe, SendGrid, QuickBooks" />
              {integrations.length > 1 && <button onClick={() => removeListItem(setIntegrations, i)} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>}
            </div>
          ))}
          <button onClick={() => addListItem(setIntegrations)} className="text-xs text-brand-deep hover:text-brand flex items-center gap-1"><Plus className="w-3 h-3" /> Add integration</button>
        </div>
      </section>

      {/* Section 4: Entities */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-white">Data Entities</h2>
            <p className="text-gray-500 text-xs">Define the core objects in the system. Leave empty to let DF infer from the problem statement.</p>
          </div>
          <button onClick={addEntity} className="flex items-center gap-1 px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-gray-300 hover:text-white hover:border-slate-600">
            <Plus className="w-3.5 h-3.5" /> Add Entity
          </button>
        </div>
        {entities.map((entity, ei) => (
          <div key={ei} className="p-4 bg-slate-800/50 border border-slate-700/50 rounded-lg space-y-3">
            <div className="flex gap-3">
              <input className={inputClass} value={entity.name} onChange={e => setEntities(prev => prev.map((ent, i) => i === ei ? { ...ent, name: e.target.value } : ent))} placeholder="Entity name (e.g., Student, MenuItem)" />
              <button onClick={() => setEntities(prev => prev.filter((_, i) => i !== ei))} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>
            </div>
            <input className={inputClass} value={entity.description} onChange={e => setEntities(prev => prev.map((ent, i) => i === ei ? { ...ent, description: e.target.value } : ent))} placeholder="Description" />
            <div>
              <label className="text-xs text-gray-500">Fields</label>
              {entity.fields.map((f, fi) => (
                <div key={fi} className="flex gap-2 mb-1">
                  <input className={`${inputClass} flex-1`} value={f.name} onChange={e => {
                    const newFields = [...entity.fields];
                    newFields[fi] = { ...f, name: e.target.value };
                    setEntities(prev => prev.map((ent, i) => i === ei ? { ...ent, fields: newFields } : ent));
                  }} placeholder="Field name" />
                  <select className={`${inputClass} w-32`} value={f.type} onChange={e => {
                    const newFields = [...entity.fields];
                    newFields[fi] = { ...f, type: e.target.value };
                    setEntities(prev => prev.map((ent, i) => i === ei ? { ...ent, fields: newFields } : ent));
                  }}>
                    <option value="String">String</option><option value="Int">Int</option>
                    <option value="Float">Float</option><option value="Boolean">Boolean</option>
                    <option value="DateTime">DateTime</option><option value="Json">Json</option>
                    <option value="Enum">Enum</option>
                  </select>
                  {fi > 0 && <button onClick={() => {
                    setEntities(prev => prev.map((ent, i) => i === ei ? { ...ent, fields: ent.fields.filter((_, j) => j !== fi) } : ent));
                  }} className="text-red-400 hover:text-red-300"><Trash2 className="w-3.5 h-3.5" /></button>}
                </div>
              ))}
              <button onClick={() => {
                setEntities(prev => prev.map((ent, i) => i === ei ? { ...ent, fields: [...ent.fields, { name: '', type: 'String' }] } : ent));
              }} className="text-xs text-brand-deep hover:text-brand flex items-center gap-1 mt-1"><Plus className="w-3 h-3" /> Add field</button>
            </div>
          </div>
        ))}
      </section>

      {/* Section 5: Acceptance Criteria */}
      <section className="bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-white">Acceptance Criteria</h2>
            <p className="text-gray-500 text-xs">Define what \"done\" looks like. These become your QA checklist after code generation.</p>
          </div>
          <button onClick={addCriterion} className="flex items-center gap-1 px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-gray-300 hover:text-white hover:border-slate-600">
            <Plus className="w-3.5 h-3.5" /> Add Criterion
          </button>
        </div>
        {acceptanceCriteria.map((criterion, ci) => (
          <div key={ci} className="flex gap-2">
            <input className={`${inputClass} flex-1`} value={criterion.description} onChange={e => {
              setAcceptanceCriteria(prev => prev.map((c, i) => i === ci ? { ...c, description: e.target.value } : c));
            }} placeholder="e.g., Admin can create a new menu item with allergen tags" />
            <select className={`${inputClass} w-28`} value={criterion.priority} onChange={e => {
              setAcceptanceCriteria(prev => prev.map((c, i) => i === ci ? { ...c, priority: e.target.value } : c));
            }}>
              <option value="must">Must Have</option>
              <option value="should">Should Have</option>
              <option value="nice_to_have">Nice to Have</option>
            </select>
            <button onClick={() => setAcceptanceCriteria(prev => prev.filter((_, i) => i !== ci))} className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></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..." />
      </section>

      {/* Submit */}
      <div className="flex justify-end gap-3">
        <Link href="/dark-factory/app/intake" className="px-4 py-2 text-gray-400 hover:text-white transition-colors">Cancel</Link>
        <button onClick={handleSubmit} disabled={saving}
          className="flex items-center gap-2 px-6 py-2 bg-brand-deep hover:bg-brand-deep/80 disabled:opacity-50 text-white rounded-lg font-medium transition-colors">
          {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
          {saving ? 'Creating...' : 'Create Intake'}
        </button>
      </div>
    </div>
  );
}
