'use client';
import { useState, useEffect, useTransition } from 'react';
import { useRouter } from 'next/navigation';

type FormTemplate = { id: string; name: string; filename: string };

export function AddDocumentModal({ clientId, onClose }: { clientId: string; onClose: () => void }) {
  const [templates, setTemplates] = useState<FormTemplate[]>([]);
  const [query, setQuery] = useState('');
  const [docName, setDocName] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState<FormTemplate | null>(null);
  const [customFile, setCustomFile] = useState<File | null>(null);
  const [isPending, startTransition] = useTransition();
  const [saving, setSaving] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetch('/api/forms-library')
      .then(r => r.json())
      .then(setTemplates)
      .catch(console.error);
  }, []);

  const filtered = templates.filter(t =>
    t.name.toLowerCase().includes(query.toLowerCase())
  );

  const handleSelectTemplate = (t: FormTemplate) => {
    setSelectedTemplate(t);
    setCustomFile(null);
    setDocName(t.name);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0] ?? null;
    setCustomFile(file);
    setSelectedTemplate(null);
    if (file) setDocName(file.name.replace(/\.pdf$/i, ''));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!docName.trim() || (!selectedTemplate && !customFile)) return;

    setSaving(true);
    try {
      if (customFile) {
        const fd = new FormData();
        fd.append('clientId', clientId);
        fd.append('name', docName.trim());
        fd.append('file', customFile);
        await fetch('/api/documents', { method: 'POST', body: fd });
      } else {
        await fetch('/api/documents', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ clientId, name: docName.trim(), formTemplateId: selectedTemplate!.id }),
        });
      }
      startTransition(() => router.refresh());
      onClose();
    } catch (err) {
      console.error(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 p-6">
        <h2 className="text-xl font-semibold mb-4">Add Document</h2>

        <input
          type="text"
          placeholder="Search forms..."
          value={query}
          onChange={e => setQuery(e.target.value)}
          className="w-full border rounded px-3 py-2 mb-3 text-sm"
        />

        <ul className="border rounded max-h-48 overflow-y-auto mb-4">
          {filtered.length === 0 && (
            <li className="px-3 py-2 text-sm text-gray-500">No forms found</li>
          )}
          {filtered.map(t => (
            <li
              key={t.id}
              onClick={() => handleSelectTemplate(t)}
              className={`px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 ${selectedTemplate?.id === t.id ? 'bg-blue-50 font-medium' : ''}`}
            >
              {t.name}
            </li>
          ))}
        </ul>

        <div className="mb-4">
          <label className="block text-sm font-medium mb-1">Or upload a custom PDF</label>
          <div className="flex items-center gap-3">
            <label className="cursor-pointer px-4 py-2 text-sm border border-gray-300 rounded bg-white hover:bg-gray-50 font-medium">
              Browse files
              <input type="file" accept="application/pdf" onChange={handleFileChange} className="hidden" />
            </label>
            {customFile && (
              <span className="text-sm text-gray-600 truncate max-w-xs">{customFile.name}</span>
            )}
          </div>
        </div>

        <form onSubmit={handleSubmit}>
          <label className="block text-sm font-medium mb-1">Document name</label>
          <input
            type="text"
            value={docName}
            onChange={e => setDocName(e.target.value)}
            required
            className="w-full border rounded px-3 py-2 mb-4 text-sm"
            placeholder="e.g. 123 Main St Purchase Agreement"
          />

          <div className="flex gap-3 justify-end">
            <button type="button" onClick={onClose} className="px-4 py-2 text-sm border rounded hover:bg-gray-50">
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving || (!selectedTemplate && !customFile) || !docName.trim()}
              className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
            >
              {saving ? 'Saving...' : 'Add Document'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
