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

interface PreparePanelProps {
  docId: string;
  defaultEmail: string;
  clientName: string;
  currentStatus: string;
}

function parseEmails(raw: string | undefined): string[] {
  return (raw ?? '').split(/[\n,]+/).map((e) => e.trim()).filter(Boolean);
}

function isValidEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export function PreparePanel({ docId, defaultEmail, clientName, currentStatus }: PreparePanelProps) {
  const router = useRouter();
  const [recipients, setRecipients] = useState(defaultEmail ?? '');
  // Sync if defaultEmail arrives after initial render (streaming / hydration timing)
  useEffect(() => {
    if (defaultEmail) setRecipients(defaultEmail);
  }, [defaultEmail]);
  const [textFillData, setTextFillData] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);

  if (currentStatus !== 'Draft') {
    return (
      <div className="rounded-lg border border-gray-200 p-4 bg-gray-50 text-sm text-gray-500">
        Document status is <strong>{currentStatus}</strong> — preparation is only available for Draft documents.
      </div>
    );
  }

  async function handlePrepare() {
    setLoading(true);
    setResult(null);

    const emailAddresses = parseEmails(recipients);

    if (emailAddresses.length === 0) {
      setResult({ ok: false, message: 'Enter at least one recipient email.' });
      setLoading(false);
      return;
    }

    const invalid = emailAddresses.filter((e) => !isValidEmail(e));
    if (invalid.length > 0) {
      setResult({ ok: false, message: `Invalid email(s): ${invalid.join(', ')}` });
      setLoading(false);
      return;
    }

    try {
      const res = await fetch(`/api/documents/${docId}/prepare`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ textFillData, emailAddresses }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({ error: 'Unknown error' }));
        setResult({ ok: false, message: err.error ?? 'Prepare failed' });
      } else {
        setResult({ ok: true, message: 'Document prepared. Status updated to Sent.' });
        router.refresh();
      }
    } catch (e) {
      setResult({ ok: false, message: String(e) });
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="rounded-lg border border-gray-200 p-4 space-y-4">
      <h2 className="font-semibold text-gray-900">Prepare Document</h2>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Recipients
        </label>
        <textarea
          value={recipients}
          onChange={(e) => setRecipients(e.target.value)}
          rows={2}
          className="w-full border rounded px-2 py-1.5 text-sm resize-none"
          placeholder="email@example.com"
        />
        <p className="text-xs text-gray-400 mt-0.5">
          To add more recipients, separate each email with a comma
        </p>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">Text fill fields</label>
        <TextFillForm onChange={setTextFillData} />
      </div>

      <button
        onClick={handlePrepare}
        disabled={loading || parseEmails(recipients).length === 0}
        className="w-full py-2 px-4 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium"
        type="button"
      >
        {loading ? 'Preparing...' : 'Prepare and Send'}
      </button>

      {result && (
        <p className={`text-sm ${result.ok ? 'text-green-600' : 'text-red-600'}`}>
          {result.message}
        </p>
      )}
    </div>
  );
}
