'use client';

import { useEffect, useState } from 'react';
import { CheckCircle2, PenLine } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch, adminApiOpenPdf } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { fillTemplate } from '@/lib/template-placeholders';
import { useLiveRefresh } from '@/lib/realtime';
import AttachmentPicker, { Attachment } from '@/components/AttachmentPicker';
import AiPolishButton from '@/components/AiPolishButton';
import SignaturePad, { SignatureValue } from '@/components/SignaturePad';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type Template = { id: number; name: string; category: string; body: string; isBuiltIn: boolean };
type LetterRow = { id: number; title: string; recipientName: string; createdAt: string; isSigned: boolean; createdBy: { name: string } | null };

const emptyForm = { title: '', recipientName: '', recipientAddress: '', body: '' };

export default function LetterComposerPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [templates, setTemplates] = useState<Template[]>([]);
  const [letters, setLetters] = useState<LetterRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [form, setForm] = useState(emptyForm);
  const [attachments, setAttachments] = useState<Attachment[]>([]);
  const [signature, setSignature] = useState<SignatureValue>(null);
  const [saving, setSaving] = useState(false);

  const [emailTarget, setEmailTarget] = useState<LetterRow | null>(null);
  const [emailTo, setEmailTo] = useState('');
  const [emailCc, setEmailCc] = useState('');
  const [emailing, setEmailing] = useState(false);

  // Signing an already-saved (unsigned) letter.
  const [signTarget, setSignTarget] = useState<LetterRow | null>(null);
  const [signValue, setSignValue] = useState<SignatureValue>(null);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    try {
      const [t, l] = await Promise.all([
        adminApiFetch('/admin/letters/templates', accessToken, appSecretProof),
        adminApiFetch('/admin/letters', accessToken, appSecretProof),
      ]);
      setTemplates(t.templates || []);
      setLetters(l.letters || []);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps
  useLiveRefresh(['letters'], load);

  function applyTemplate(templateId: string) {
    const t = templates.find((x) => x.id === Number(templateId));
    if (!t) return;
    const values = { recipientName: form.recipientName || '{{recipientName}}', date: new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' }) };
    setForm((f) => ({ ...f, title: f.title || t.name, body: fillTemplate(t.body, values) }));
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      const d = await adminApiFetch('/admin/letters', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ ...form, attachments, signature: signature || undefined }),
      });
      show('success', signature ? 'Signed letter created.' : 'Draft saved — it must be signed before it can be sent.');
      setForm(emptyForm); setAttachments([]); setSignature(null);
      load();
      await adminApiOpenPdf(`/admin/letters/${d.letter.id}/pdf`, accessToken, appSecretProof);
    } catch { show('error', 'Could not create that letter.'); }
    finally { setSaving(false); }
  }

  async function downloadPdf(id: number) {
    if (!accessToken || !appSecretProof) return;
    try { await adminApiOpenPdf(`/admin/letters/${id}/pdf`, accessToken, appSecretProof); }
    catch { show('error', 'Could not open that letter.'); }
  }

  async function saveSignature() {
    if (!accessToken || !appSecretProof || !signTarget || !signValue) return;
    try {
      await adminApiFetch(`/admin/letters/${signTarget.id}/signature`, accessToken, appSecretProof, { method: 'PUT', body: JSON.stringify(signValue) });
      show('success', 'Signature added.');
      setSignTarget(null); setSignValue(null); load();
    } catch { show('error', 'Could not save that signature.'); }
  }

  async function submitEmail(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !emailTarget) return;
    setEmailing(true);
    try {
      await adminApiFetch(`/admin/letters/${emailTarget.id}/email`, accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ toEmail: emailTo, ccEmail: emailCc || undefined }),
      });
      show('success', 'Letter delivered to the mail server.');
      setEmailTarget(null); setEmailTo(''); setEmailCc('');
    } catch (err) {
      const m = (err as Error).message;
      show('error', m === 'SIGNATURE_REQUIRED' ? 'This letter has no signature — sign it first.'
        : m === 'REQUEST_FAILED_503' ? 'NOT sent — the info@ mailbox has no SMTP login yet.'
        : 'Could not send that letter — the mail server refused it.');
    } finally { setEmailing(false); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">Letters &bull; admin.lussavara.co.tz</h1>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <form onSubmit={submit} className="lg:col-span-2 bg-white border border-brand-border rounded-xl p-4 space-y-3">
          <select onChange={(e) => applyTemplate(e.target.value)} defaultValue=""
            className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-sm">
            <option value="">Use a template…</option>
            {templates.map((t) => <option key={t.id} value={t.id}>{t.category} — {t.name}</option>)}
          </select>

          <input required placeholder="Letter title / subject (e.g. Offer of Employment)" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })}
            className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
          <input required placeholder="Recipient name" value={form.recipientName} onChange={(e) => setForm({ ...form, recipientName: e.target.value })}
            className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
          <textarea placeholder="Recipient address (optional, one line per row)" value={form.recipientAddress} onChange={(e) => setForm({ ...form, recipientAddress: e.target.value })}
            rows={2} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
          <textarea required placeholder="Letter body — separate paragraphs with a blank line" value={form.body} onChange={(e) => setForm({ ...form, body: e.target.value })}
            rows={12} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
          <AiPolishButton text={form.body} kind="letter" onAccept={(t) => setForm((f) => ({ ...f, body: t }))} />

          <div>
            <p className="text-xs font-semibold flex items-center gap-1.5 mb-1"><PenLine size={13} /> Signature <span className="text-brand-red">— required before the letter can be sent</span></p>
            <SignaturePad value={signature} onChange={setSignature} />
          </div>

          <AttachmentPicker attachments={attachments} onChange={setAttachments} />
          <p className="text-[10px] text-gray-400 -mt-1">Extra files travel with the letter when it is e-mailed, next to the generated PDF.</p>

          <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60 transition-transform hover:scale-[1.01]">
            {saving ? 'Generating…' : signature ? 'Generate Signed Letter PDF' : 'Save Draft & Preview PDF (unsigned)'}
          </button>
        </form>

        <div className="bg-white border border-brand-border rounded-xl p-4">
          <p className="text-sm font-semibold mb-2">Recent Letters</p>
          {loading ? <TableSkeleton rows={4} cols={1} /> : (
            <div className="space-y-2 max-h-[600px] overflow-y-auto">
              {letters.map((l) => (
                <div key={l.id} className="text-xs border-t border-brand-border pt-2 first:border-t-0 first:pt-0 animate-fadeInUp">
                  <p className="font-medium flex items-center gap-1.5">
                    {l.title}
                    {l.isSigned
                      ? <span className="inline-flex items-center gap-0.5 text-[9px] bg-green-100 text-green-700 rounded-full px-1.5 py-0.5"><CheckCircle2 size={9} /> SIGNED</span>
                      : <span className="text-[9px] bg-yellow-100 text-yellow-700 rounded-full px-1.5 py-0.5">UNSIGNED</span>}
                  </p>
                  <p className="text-gray-400">To {l.recipientName} &bull; {new Date(l.createdAt).toLocaleDateString()} &bull; {l.createdBy?.name}</p>
                  <div className="flex gap-3 mt-1">
                    <button onClick={() => downloadPdf(l.id)} className="text-brand-red transition-colors hover:text-red-800">PDF</button>
                    {l.isSigned
                      ? <button onClick={() => setEmailTarget(l)} className="text-brand-red transition-colors hover:text-red-800">Email</button>
                      : <button onClick={() => setSignTarget(l)} className="text-brand-red transition-colors hover:text-red-800">Sign to enable sending</button>}
                  </div>
                </div>
              ))}
              {letters.length === 0 && <p className="text-xs text-gray-400">No letters yet.</p>}
            </div>
          )}
        </div>
      </div>

      {signTarget && (
        <Modal title={`Sign "${signTarget.title}"`} onClose={() => { setSignTarget(null); setSignValue(null); }} wide>
          <div className="space-y-3">
            <SignaturePad value={signValue} onChange={setSignValue} />
            <button onClick={saveSignature} disabled={!signValue} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-50">Add signature to letter</button>
          </div>
        </Modal>
      )}

      {emailTarget && (
        <Modal title={`Email "${emailTarget.title}"`} onClose={() => setEmailTarget(null)}>
          <form onSubmit={submitEmail} className="space-y-3">
            <input required type="email" autoFocus placeholder="Recipient email" value={emailTo} onChange={(e) => setEmailTo(e.target.value)}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input type="email" placeholder="CC (optional)" value={emailCc} onChange={(e) => setEmailCc(e.target.value)}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <p className="text-[10px] text-gray-400">Sent from info@lussavara.co.tz with the signed PDF (and any extra files) attached.</p>
            <button disabled={emailing} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {emailing ? 'Sending…' : 'Send Letter'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
