import React, { useState, useEffect } from 'react';
import { api } from '../api';

export default function EmailSettings() {
  const [config, setConfig] = useState(null);
  const [stats, setStats] = useState(null);
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [testEmail, setTestEmail] = useState('');
  const [testStatus, setTestStatus] = useState('');
  const [inbound, setInbound] = useState({ enabled: false, folder: 'INBOX', prefix: 'tf-' });

  const load = async () => {
    try {
      const [cfg, st, lg] = await Promise.all([api.email.config(), api.email.stats(), api.email.log()]);
      setConfig(cfg);
      setStats(st);
      setLogs(lg);
      setInbound({ enabled: !!cfg.inbound_enabled, folder: cfg.inbound_folder || 'INBOX', prefix: cfg.board_email_prefix || 'tf-' });
    } catch {}
    setLoading(false);
  };

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

  const sendTest = async () => {
    if (!testEmail) return;
    setTestStatus('sending...');
    try {
      await api.setup.testEmail(testEmail);
      setTestStatus('✅ Sent!');
      load();
    } catch (err) {
      setTestStatus(`❌ ${err.message}`);
    }
    setTimeout(() => setTestStatus(''), 5000);
  };

  const saveInbound = async () => {
    try {
      await api.setup.updateInbound(inbound);
      load();
    } catch (err) { alert(err.message); }
  };

  const pollNow = async () => {
    try {
      await api.email.poll();
      load();
      alert('Inbox polled successfully');
    } catch (err) { alert(err.message); }
  };

  if (loading) return <div className="flex justify-center py-12"><div className="animate-spin h-8 w-8 border-4 border-brand-500 border-t-transparent rounded-full"></div></div>;

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold text-gray-900 mb-6">📧 Email Settings</h1>

      {/* SMTP Config */}
      <div className="bg-white rounded-xl border border-gray-200 p-5 mb-6 shadow-sm">
        <h2 className="font-semibold text-gray-900 mb-3">SMTP Configuration</h2>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-4">
          <div>
            <label className="block text-xs text-gray-500 mb-1">Host</label>
            <p className="text-sm font-mono bg-gray-100 px-3 py-2 rounded-lg">{config?.smtp_host}</p>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Port</label>
            <p className="text-sm font-mono bg-gray-100 px-3 py-2 rounded-lg">{config?.smtp_port}</p>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Email</label>
            <p className="text-sm font-mono bg-gray-100 px-3 py-2 rounded-lg">{config?.email}</p>
          </div>
        </div>
        <div className="flex items-center gap-2 mb-3">
          <input type="email" value={testEmail} onChange={e => setTestEmail(e.target.value)} placeholder="Send test to..." className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-500" />
          <button onClick={sendTest} disabled={testStatus === 'sending...'} className="bg-brand-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
            Send Test
          </button>
          {testStatus && <span className="text-sm">{testStatus}</span>}
        </div>
        <p className="text-xs text-gray-400">App password is stored encrypted. Configure via the setup wizard to change it.</p>
      </div>

      {/* Stats */}
      {stats && (
        <div className="grid grid-cols-3 gap-4 mb-6">
          <div className="bg-white rounded-xl border border-gray-200 p-4 text-center shadow-sm">
            <p className="text-2xl font-bold text-brand-600">{stats.sent}</p>
            <p className="text-xs text-gray-500 mt-1">Emails Sent</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-200 p-4 text-center shadow-sm">
            <p className="text-2xl font-bold text-green-600">{stats.received}</p>
            <p className="text-xs text-gray-500 mt-1">Emails Processed</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-200 p-4 text-center shadow-sm">
            <p className="text-2xl font-bold text-red-600">{stats.failed}</p>
            <p className="text-xs text-gray-500 mt-1">Failed</p>
          </div>
        </div>
      )}

      {/* Inbound Settings */}
      <div className="bg-white rounded-xl border border-gray-200 p-5 mb-6 shadow-sm">
        <div className="flex items-center justify-between mb-3">
          <h2 className="font-semibold text-gray-900">📥 Inbound Email</h2>
          <button onClick={pollNow} className="text-sm text-brand-600 hover:bg-brand-50 px-3 py-1 rounded-lg font-medium">Poll Now</button>
        </div>
        <p className="text-sm text-gray-500 mb-4">Process incoming emails to create cards and add comments. Enable IMAP in your Google account settings.</p>
        <div className="space-y-3">
          <label className="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" checked={inbound.enabled} onChange={e => setInbound({ ...inbound, enabled: e.target.checked })} className="rounded border-gray-300 text-brand-600 focus:ring-brand-500" />
            <span className="text-sm font-medium text-gray-700">Enable inbound email processing</span>
          </label>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs text-gray-500 mb-1">IMAP Folder</label>
              <input type="text" value={inbound.folder} onChange={e => setInbound({ ...inbound, folder: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-500" />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Board Email Prefix</label>
              <input type="text" value={inbound.prefix} onChange={e => setInbound({ ...inbound, prefix: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-500" />
            </div>
          </div>
          <button onClick={saveInbound} className="bg-brand-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-brand-700">Save Inbound Settings</button>
        </div>
        <div className="mt-4 p-3 bg-blue-50 rounded-lg text-xs text-blue-700">
          <strong>How it works:</strong> Send an email with subject <code className="bg-blue-100 px-1 rounded">[{inbound.prefix}board-name] Card title</code> to create a card.
          Reply to notification emails to add comments.
        </div>
      </div>

      {/* Email Log */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-gray-200">
          <h2 className="font-semibold text-gray-900">📋 Email Log</h2>
        </div>
        <div className="max-h-80 overflow-y-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50">
                <th className="text-left px-4 py-2 text-xs font-semibold text-gray-500">Direction</th>
                <th className="text-left px-4 py-2 text-xs font-semibold text-gray-500">To/From</th>
                <th className="text-left px-4 py-2 text-xs font-semibold text-gray-500">Subject</th>
                <th className="text-left px-4 py-2 text-xs font-semibold text-gray-500">Status</th>
                <th className="text-left px-4 py-2 text-xs font-semibold text-gray-500">Time</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {logs.map(l => (
                <tr key={l.id} className="hover:bg-gray-50">
                  <td className="px-4 py-2">
                    <span className={`text-xs px-2 py-0.5 rounded-full ${l.direction === 'sent' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'}`}>
                      {l.direction}
                    </span>
                  </td>
                  <td className="px-4 py-2 text-sm text-gray-600 max-w-48 truncate">{l.direction === 'sent' ? l.to_email : l.from_email}</td>
                  <td className="px-4 py-2 text-sm text-gray-600 max-w-64 truncate">{l.subject}</td>
                  <td className="px-4 py-2">
                    <span className={`text-xs px-2 py-0.5 rounded-full ${l.status === 'sent' || l.status === 'processed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                      {l.status}
                    </span>
                  </td>
                  <td className="px-4 py-2 text-xs text-gray-400">{new Date(l.created_at).toLocaleString()}</td>
                </tr>
              ))}
              {logs.length === 0 && <tr><td colSpan={5} className="px-4 py-8 text-center text-sm text-gray-400">No emails sent or received yet</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
