/* eslint-disable */
// Document Safe — category filter chips + grid of document cards

const CATEGORY_TONE = {
  Appliances: "orange",
  Medical:    "danger",
  Insurance:  "info",
  Financial:  "success",
  Legal:      "purple",
  Education:  "indigo",
  Warranty:   "warn",
  Other:      "gray",
};

const SEED_DOCS = [
  { id: 1, title: "Furnace manual",              category: "Appliances", link: "https://example.com/manual",   expirationDate: null,         notes: "PDF on Google Drive, family folder." },
  { id: 2, title: "Home insurance policy",       category: "Insurance",  link: "https://example.com/policy",   expirationDate: "Sep 12, 2026", notes: "Renews annually." },
  { id: 3, title: "Car warranty",                category: "Warranty",   link: "https://example.com/warranty", expirationDate: "Jun 04, 2026", notes: null },
  { id: 4, title: "Refrigerator user guide",     category: "Appliances", link: null,                            expirationDate: null,         notes: "Hard copy in the kitchen drawer." },
  { id: 5, title: "Mortgage statement",          category: "Financial",  link: "https://example.com/mortgage", expirationDate: null,         notes: null },
  { id: 6, title: "Vehicle registration",        category: "Legal",      link: "https://example.com/reg",      expirationDate: "Jul 22, 2026", notes: null },
  { id: 7, title: "Pediatrician contact card",   category: "Medical",    link: null,                            expirationDate: null,         notes: "Dr. Mehra — call number." },
];

const DocCard = ({ doc, onDelete, onEdit }) => {
  const tone = CATEGORY_TONE[doc.category] || "gray";
  return (
    <Card>
      <div className="flex justify-between items-start mb-3 gap-2">
        <div className="flex-1">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white">{doc.title}</h3>
          <div className="mt-2"><Pill tone={tone}>{doc.category}</Pill></div>
        </div>
      </div>
      {doc.link && (
        <a href={doc.link} target="_blank" rel="noopener noreferrer" className="text-blue-600 dark:text-blue-400 hover:underline text-sm mb-2 inline-block">
          🔗 View Document
        </a>
      )}
      {doc.files && doc.files.length > 0 && (
        <div className="mt-2 space-y-1">
          {doc.files.map((f, i) => (
            <a key={i} href={f.data} download={f.name} className="flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 hover:underline">
              📎 {f.name} <span className="text-xs text-gray-400">({(f.size / 1024).toFixed(0)} KB)</span>
            </a>
          ))}
        </div>
      )}
      {doc.expirationDate && (
        <p className="text-xs text-gray-600 dark:text-gray-400 mt-2">
          ⏰ Expires: {doc.expirationDate}
        </p>
      )}
      {doc.notes && (
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-3 italic">"{doc.notes}"</p>
      )}
      <div className="flex gap-3 mt-4 text-sm">
        {doc.link && <a href={doc.link} target="_blank" rel="noopener noreferrer" className="text-blue-600 dark:text-blue-400 hover:underline">Open</a>}
        <button onClick={() => onEdit(doc)} className="text-blue-600 dark:text-blue-400 hover:underline">Edit</button>
        <button onClick={() => onDelete(doc.id)} className="text-red-600 dark:text-red-400 hover:underline">Delete</button>
      </div>
    </Card>
  );
};

const DocumentSafeScreen = () => {
  const [docs, setDocs] = React.useState(() => {
    const stored = Storage.getArray('familyhub_documents', 'documents');
    return stored;
  });
  const saveDocs = (newDocs) => { setDocs(newDocs); Storage.set('familyhub_documents', { documents: newDocs }); };
  const [filter, setFilter] = React.useState("all");
  const [showAdd, setShowAdd] = React.useState(false);
  const [draft, setDraft] = React.useState({ title: "", category: "Appliances", link: "", expirationDate: "", notes: "" });
  const [docFiles, setDocFiles] = React.useState([]);
  const addDoc = () => {
    if (!draft.title.trim()) return;
    const finish = (fileData) => {
      saveDocs([...docs, { id: Date.now(), ...draft, link: draft.link || null, expirationDate: draft.expirationDate || null, notes: draft.notes || null, files: fileData }]);
      setDraft({ title: "", category: "Appliances", link: "", expirationDate: "", notes: "" });
      setDocFiles([]);
      setShowAdd(false);
    };
    if (docFiles.length > 0) {
      const fileData = [];
      let loaded = 0;
      Array.from(docFiles).forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => { fileData.push({ name: file.name, size: file.size, type: file.type, data: e.target.result }); loaded++; if (loaded === docFiles.length) finish(fileData); };
        reader.readAsDataURL(file);
      });
    } else { finish([]); }
  };
  const deleteDoc = (id) => { if (!window.confirm("Are you sure you want to delete this document?")) return; saveDocs(docs.filter(d => d.id !== id)); };
  const [editDoc, setEditDoc] = React.useState(null);
  const startEditDoc = (d) => { setEditDoc({ ...d }); };
  const saveEditDoc = () => {
    if (!editDoc.title.trim()) return;
    saveDocs(docs.map(d => d.id === editDoc.id ? { ...d, title: editDoc.title.trim(), category: editDoc.category, link: editDoc.link || null, expirationDate: editDoc.expirationDate || null, notes: editDoc.notes || null } : d));
    setEditDoc(null);
  };
  const categories = [...new Set(docs.map(d => d.category))];
  const filtered = filter === "all" ? docs : docs.filter(d => d.category === filter);

  const FilterChip = ({ id, label, count, active }) => (
    <button
      onClick={() => setFilter(id)}
      className={
        "px-4 py-2 rounded-full font-medium text-sm transition-colors " +
        (active
          ? "bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200"
          : "bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600")
      }
    >
      {label} ({count})
    </button>
  );

  return (
    <section className="p-4 md:p-6">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-3xl font-bold text-gray-900 dark:text-white">Document Safe</h2>
        <BtnPrimary onClick={() => setShowAdd(true)}>+ Add Document</BtnPrimary>
      </div>

      {showAdd && (
        <Modal title="Add Document" onClose={() => setShowAdd(false)} onSubmit={addDoc} submitLabel="Add Document">
          <div className="space-y-4">
            <div><Label required>Title</Label><Input placeholder="e.g. Home insurance policy" value={draft.title} onChange={e => setDraft({...draft, title: e.target.value})} autoFocus /></div>
            <div>
              <Label>Category</Label>
              <Select value={draft.category} onChange={e => setDraft({...draft, category: e.target.value})}>
                {["Appliances","Medical","Insurance","Financial","Legal","Education","Warranty","Other"].map(c => <option key={c} value={c}>{c}</option>)}
              </Select>
            </div>
            <div><Label>Link</Label><Input placeholder="https://..." value={draft.link} onChange={e => setDraft({...draft, link: e.target.value})} /></div>
            <div><Label>Expiration Date</Label><Input type="date" value={draft.expirationDate} onChange={e => setDraft({...draft, expirationDate: e.target.value})} /></div>
            <div><Label>Notes</Label><Textarea rows={2} placeholder="Where is it stored?" value={draft.notes} onChange={e => setDraft({...draft, notes: e.target.value})} /></div>
            <div>
              <Label>Upload Files</Label>
              <input type="file" multiple onChange={e => setDocFiles(e.target.files)} className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm" />
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Upload one or more documents (PDFs, images, etc.)</p>
            </div>
          </div>
        </Modal>
      )}

      {editDoc && (
        <Modal title="Edit Document" onClose={() => setEditDoc(null)} onSubmit={saveEditDoc} submitLabel="Save">
          <div className="space-y-4">
            <div><Label required>Title</Label><Input value={editDoc.title} onChange={e => setEditDoc({...editDoc, title: e.target.value})} autoFocus /></div>
            <div>
              <Label>Category</Label>
              <Select value={editDoc.category} onChange={e => setEditDoc({...editDoc, category: e.target.value})}>
                {["Appliances","Medical","Insurance","Financial","Legal","Education","Warranty","Other"].map(c => <option key={c} value={c}>{c}</option>)}
              </Select>
            </div>
            <div><Label>Link</Label><Input value={editDoc.link || ''} onChange={e => setEditDoc({...editDoc, link: e.target.value})} /></div>
            <div><Label>Expiration Date</Label><Input type="date" value={editDoc.expirationDate || ''} onChange={e => setEditDoc({...editDoc, expirationDate: e.target.value})} /></div>
            <div><Label>Notes</Label><Textarea rows={2} value={editDoc.notes || ''} onChange={e => setEditDoc({...editDoc, notes: e.target.value})} /></div>
          </div>
        </Modal>
      )}

      <div className="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6">
        <p className="text-sm text-blue-900 dark:text-blue-100">
          💡 <strong>Tip:</strong> This safe stores document references and metadata, not sensitive files. Never store passwords, SSNs, or credit card numbers here.
        </p>
      </div>

      <div className="flex gap-2 mb-6 flex-wrap">
        <FilterChip id="all" label="All" count={docs.length} active={filter === "all"} />
        {categories.map((c) => (
          <FilterChip key={c} id={c} label={c} count={docs.filter(d => d.category === c).length} active={filter === c} />
        ))}
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {filtered.map((doc) => <DocCard key={doc.id} doc={doc} onDelete={deleteDoc} onEdit={startEditDoc} />)}
      </div>
    </section>
  );
};

window.DocumentSafeScreen = DocumentSafeScreen;
