'use client';
import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';

const DOC_TYPES = ['sales_agreement','contract','po','other'];

export default function DocumentsPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [docs, setDocs] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);
  const [filterType, setFilterType] = useState('');
  const [filterYear, setFilterYear] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({ document_type: 'sales_agreement', title: '', year: String(new Date().getFullYear()), person: '', file_url: '', notes: '' });

  useEffect(() => { if (!loading && !user) router.push('/login?next=' + encodeURIComponent(window.location.pathname)); }, [user, loading, router]);

  const load = useCallback(async () => {
    setLoadingData(true);
    const params = new URLSearchParams();
    if (filterType) params.set('type', filterType);
    if (filterYear) params.set('year', filterYear);
    const r = await fetch(`/api/accounting/documents?${params}`);
    const d = await r.json();
    setDocs(d.documents ?? []);
    setLoadingData(false);
  }, [filterType, filterYear]);

  useEffect(() => { if (user) load(); }, [user, load]);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    await fetch('/api/accounting/documents', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...form, year: form.year ? parseInt(form.year) : null }) });
    setSaving(false);
    setShowForm(false);
    load();
  }

  const years = Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i);

  if (loading) return <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center"><div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" /></div>;
  if (!user) return null;

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-white p-6">
      <div className="max-w-5xl mx-auto space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">Document Vault</h1>
            <Link href="/admin/accounting" className="text-xs text-[#555] hover:text-[#888]">← Accounting</Link>
          </div>
          <button onClick={() => setShowForm(true)} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500">+ Upload Document</button>
        </div>

        {/* Year tabs */}
        <div className="flex gap-1 flex-wrap">
          <button onClick={() => setFilterYear('')} className={`px-3 py-1 rounded text-xs ${!filterYear ? 'bg-[#1D4ED8] text-white' : 'bg-[#111] border border-[#DCE6F2] text-[#888]'}`}>All Years</button>
          {years.map(y => (
            <button key={y} onClick={() => setFilterYear(String(y))} className={`px-3 py-1 rounded text-xs ${filterYear === String(y) ? 'bg-[#1D4ED8] text-white' : 'bg-[#111] border border-[#DCE6F2] text-[#888]'}`}>{y}</button>
          ))}
        </div>

        <div className="flex gap-2">
          <select value={filterType} onChange={e => setFilterType(e.target.value)} className="px-2 py-1 bg-[#111] border border-[#DCE6F2] rounded text-xs text-[#888] focus:outline-none">
            <option value="">All Types</option>
            {DOC_TYPES.map(t => <option key={t} value={t}>{t.replace(/_/g, ' ')}</option>)}
          </select>
        </div>

        {showForm && (
          <form onSubmit={handleCreate} className="bg-[#111] border border-[#DCE6F2] rounded-lg p-4 space-y-3">
            <h3 className="text-sm font-semibold">Upload Document</h3>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs text-[#888] block mb-1">Type</label>
                <select value={form.document_type} onChange={e => setForm(p => ({ ...p, document_type: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none">
                  {DOC_TYPES.map(t => <option key={t} value={t}>{t.replace(/_/g, ' ')}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs text-[#888] block mb-1">Title *</label>
                <input required value={form.title} onChange={e => setForm(p => ({ ...p, title: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
              </div>
              {form.document_type === 'sales_agreement' && (
                <>
                  <div>
                    <label className="text-xs text-[#888] block mb-1">Person *</label>
                    <input required value={form.person} onChange={e => setForm(p => ({ ...p, person: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
                  </div>
                  <div>
                    <label className="text-xs text-[#888] block mb-1">Year *</label>
                    <input type="number" required value={form.year} onChange={e => setForm(p => ({ ...p, year: e.target.value }))} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
                  </div>
                </>
              )}
              <div className="col-span-2">
                <label className="text-xs text-[#888] block mb-1">File URL</label>
                <input value={form.file_url} onChange={e => setForm(p => ({ ...p, file_url: e.target.value }))} placeholder="https://…" className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
              </div>
              <div className="col-span-2">
                <label className="text-xs text-[#888] block mb-1">Notes</label>
                <textarea value={form.notes} onChange={e => setForm(p => ({ ...p, notes: e.target.value }))} rows={2} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]" />
              </div>
            </div>
            <div className="flex gap-2">
              <button type="submit" disabled={saving} className="px-3 py-1.5 bg-[#1D4ED8] rounded text-xs font-medium hover:bg-blue-500 disabled:opacity-50">{saving ? 'Saving…' : 'Save Document'}</button>
              <button type="button" onClick={() => setShowForm(false)} className="px-3 py-1.5 bg-[#FFFFFF] border border-[#DCE6F2] rounded text-xs text-[#888] hover:text-white">Cancel</button>
            </div>
          </form>
        )}

        <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#FFFFFF]">
                {['Type','Title','Person','Year','Date',''].map(h => (
                  <th key={h} className="px-4 py-2 text-left text-xs text-[#555] font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loadingData ? (
                <tr><td colSpan={6} className="px-4 py-8 text-center text-[#555] text-xs">Loading…</td></tr>
              ) : docs.length === 0 ? (
                <tr><td colSpan={6} className="px-4 py-8 text-center text-[#555] text-xs">No documents found</td></tr>
              ) : docs.map((d: any) => (
                <tr key={d.id} className="border-b border-[#FFFFFF] hover:bg-[#FFFFFF]">
                  <td className="px-4 py-2 text-[#888] text-xs capitalize">{d.document_type?.replace(/_/g, ' ')}</td>
                  <td className="px-4 py-2 text-white text-xs">{d.title}</td>
                  <td className="px-4 py-2 text-[#ccc] text-xs">{d.person ?? '—'}</td>
                  <td className="px-4 py-2 text-[#888] text-xs">{d.year ?? '—'}</td>
                  <td className="px-4 py-2 text-[#555] text-xs">{d.uploaded_at ? new Date(d.uploaded_at).toLocaleDateString() : '—'}</td>
                  <td className="px-4 py-2 flex gap-2">
                    {d.file_url && <a href={d.file_url} target="_blank" rel="noopener noreferrer" className="text-xs text-[#1D4ED8] hover:underline">Download</a>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
