'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Plus, FileText, Clock, CheckCircle, AlertTriangle, Eye, ArrowRight, Search, Filter } from 'lucide-react';

interface Intake {
  id: string;
  title: string;
  clientName: string | null;
  clientCompany: string | null;
  businessDomain: string;
  gate: string;
  complexityScore: number | null;
  estimatedCost: number | null;
  targetLanguage: string;
  targetDatabase: string;
  createdAt: string;
  _count: { revisionLog: number };
}

const GATE_DISPLAY: Record<string, { label: string; color: string; icon: typeof Clock }> = {
  intake_draft: { label: 'Draft', color: 'text-gray-400 bg-gray-400/10', icon: FileText },
  intake_revision: { label: 'Revision Needed', color: 'text-amber-400 bg-amber-400/10', icon: AlertTriangle },
  intake_approved: { label: 'Intake Approved', color: 'text-green-400 bg-green-400/10', icon: CheckCircle },
  visuals_generated: { label: 'Visuals Ready', color: 'text-blue-400 bg-blue-400/10', icon: Eye },
  visuals_revision: { label: 'Visual Revision', color: 'text-amber-400 bg-amber-400/10', icon: AlertTriangle },
  visuals_approved: { label: 'Visuals Approved', color: 'text-green-400 bg-green-400/10', icon: CheckCircle },
  code_generating: { label: 'Generating Code', color: 'text-orange-400 bg-orange-400/10', icon: Clock },
  code_review: { label: 'Code Review', color: 'text-blue-400 bg-blue-400/10', icon: Eye },
  deliverables_defined: { label: 'Deliverables Defined', color: 'text-sky-400 bg-sky-400/10', icon: FileText },
  deliverables_revision: { label: 'Deliverable Revision', color: 'text-amber-400 bg-amber-400/10', icon: AlertTriangle },
  deliverables_approved: { label: 'Ready to Generate', color: 'text-green-400 bg-green-400/10', icon: CheckCircle },
  complete: { label: 'Complete', color: 'text-emerald-400 bg-emerald-400/10', icon: CheckCircle },
};

export default function IntakeListPage() {
  const [intakes, setIntakes] = useState<Intake[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterGate, setFilterGate] = useState<string>('all');
  const [filterDomain, setFilterDomain] = useState<string>('all');
  const [filterLanguage, setFilterLanguage] = useState<string>('all');
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    fetch('/api/dark-factory/intake')
      .then(r => r.json())
      .then(data => { setIntakes(data.intakes || []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  // Derive unique values for filter dropdowns
  const domains = Array.from(new Set(intakes.map(i => i.businessDomain))).sort();
  const languages = Array.from(new Set(intakes.map(i => i.targetLanguage))).sort();
  const gates = Object.keys(GATE_DISPLAY);

  // Apply filters
  const filtered = intakes.filter(intake => {
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      const matchesSearch = intake.title.toLowerCase().includes(q) ||
        (intake.clientCompany || '').toLowerCase().includes(q) ||
        (intake.clientName || '').toLowerCase().includes(q) ||
        intake.businessDomain.toLowerCase().includes(q);
      if (!matchesSearch) return false;
    }
    if (filterGate !== 'all' && intake.gate !== filterGate) return false;
    if (filterDomain !== 'all' && intake.businessDomain !== filterDomain) return false;
    if (filterLanguage !== 'all' && intake.targetLanguage !== filterLanguage) return false;
    return true;
  });

  const activeFilterCount = [filterGate, filterDomain, filterLanguage].filter(f => f !== 'all').length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Project Intake Pipeline</h1>
          <p className="text-gray-400 mt-1">Gate-controlled workflow: Intake → Visuals → Code → Deliverables</p>
        </div>
        <Link href="/dark-factory/app/intake/new" className="flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep/80 text-white rounded-lg transition-colors">
          <Plus className="w-4 h-4" /> New Intake
        </Link>
      </div>

      {/* Pipeline stages indicator */}
      <div className="flex items-center gap-1 text-xs text-gray-500 overflow-x-auto pb-2">
        {['Intake', 'Estimate', 'Visuals', 'Deliverables', 'Code Gen', 'Complete'].map((stage, i) => (
          <div key={stage} className="flex items-center gap-1 whitespace-nowrap">
            <span className="px-2 py-1 rounded bg-slate-800 border border-slate-700">{stage}</span>
            {i < 5 && <ArrowRight className="w-3 h-3" />}
          </div>
        ))}
      </div>

      {/* Search & Filters */}
      {intakes.length > 0 && (
        <div className="space-y-3">
          <div className="flex gap-2">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
              <input
                className="w-full bg-slate-900 border border-slate-700 rounded-lg pl-9 pr-3 py-2 text-white text-sm placeholder-gray-500 focus:border-brand-deep/50 focus:outline-none"
                placeholder="Search by title, client, domain..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
              />
            </div>
            <button
              onClick={() => setShowFilters(!showFilters)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                showFilters || activeFilterCount > 0
                  ? 'bg-brand-deep/20 text-brand border border-brand-deep/40'
                  : 'bg-slate-900 text-gray-400 border border-slate-700 hover:border-slate-600'
              }`}
            >
              <Filter className="w-4 h-4" />
              Filters{activeFilterCount > 0 && ` (${activeFilterCount})`}
            </button>
          </div>
          {showFilters && (
            <div className="flex flex-wrap gap-3 p-3 bg-slate-900 border border-slate-700 rounded-lg">
              <div>
                <label className="block text-[10px] text-gray-500 mb-1">Gate Status</label>
                <select value={filterGate} onChange={e => setFilterGate(e.target.value)}
                  className="bg-slate-800 border border-slate-600 rounded px-2 py-1.5 text-white text-xs min-w-[140px]">
                  <option value="all">All statuses</option>
                  {gates.map(g => <option key={g} value={g}>{GATE_DISPLAY[g].label}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-[10px] text-gray-500 mb-1">Domain</label>
                <select value={filterDomain} onChange={e => setFilterDomain(e.target.value)}
                  className="bg-slate-800 border border-slate-600 rounded px-2 py-1.5 text-white text-xs min-w-[140px]">
                  <option value="all">All domains</option>
                  {domains.map(d => <option key={d} value={d}>{d}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-[10px] text-gray-500 mb-1">Language</label>
                <select value={filterLanguage} onChange={e => setFilterLanguage(e.target.value)}
                  className="bg-slate-800 border border-slate-600 rounded px-2 py-1.5 text-white text-xs min-w-[140px]">
                  <option value="all">All languages</option>
                  {languages.map(l => <option key={l} value={l}>{l}</option>)}
                </select>
              </div>
              {activeFilterCount > 0 && (
                <button onClick={() => { setFilterGate('all'); setFilterDomain('all'); setFilterLanguage('all'); }}
                  className="self-end px-3 py-1.5 text-xs text-amber-400 hover:text-amber-300">Clear all</button>
              )}
            </div>
          )}
          {searchQuery || activeFilterCount > 0 ? (
            <div className="text-xs text-gray-500">{filtered.length} of {intakes.length} intakes</div>
          ) : null}
        </div>
      )}

      {loading ? (
        <div className="text-center py-12 text-gray-500">Loading intakes...</div>
      ) : intakes.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-slate-700 rounded-xl">
          <FileText className="w-12 h-12 text-gray-600 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-400">No project intakes yet</h3>
          <p className="text-gray-500 mt-1 mb-4">Create your first intake to start the gate-controlled pipeline</p>
          <Link href="/dark-factory/app/intake/new" className="inline-flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep/80 text-white rounded-lg transition-colors">
            <Plus className="w-4 h-4" /> New Intake
          </Link>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.length === 0 && (
            <div className="text-center py-8 text-gray-500 text-sm">No intakes match your filters.</div>
          )}
          {filtered.map(intake => {
            const gate = GATE_DISPLAY[intake.gate] || GATE_DISPLAY.intake_draft;
            const GateIcon = gate.icon;
            return (
              <Link key={intake.id} href={`/dark-factory/app/intake/${intake.id}`}
                className="block p-4 bg-slate-900 border border-slate-700 rounded-xl hover:border-brand-deep/50 transition-colors">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <h3 className="text-white font-semibold truncate">{intake.title}</h3>
                    <p className="text-gray-400 text-sm mt-1">
                      {intake.clientCompany || intake.clientName || 'Internal'} · {intake.businessDomain}
                    </p>
                    <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">
                      <span>{intake.targetLanguage}</span>
                      <span>·</span>
                      <span>{intake.targetDatabase}</span>
                      {intake.complexityScore && (
                        <><span>·</span><span>Complexity: {intake.complexityScore}/10</span></>
                      )}
                      {intake.estimatedCost && (
                        <><span>·</span><span>~${intake.estimatedCost.toLocaleString()}</span></>
                      )}
                    </div>
                  </div>
                  <div className={`flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium ${gate.color}`}>
                    <GateIcon className="w-3.5 h-3.5" />
                    {gate.label}
                  </div>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
