import { useEffect, useState } from 'react';
import { RefreshCw, MailPlus, Inbox, Mail } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Badge, Btn, Field, inputCls, Modal, Spinner, ErrorBox, Table } from '../components/ui';

const EMPTY_COMPOSE = { to: '', cc: '', bcc: '', subject: '', text: '' };
const EMPTY_ACCOUNT = {
  email: '', name: '', imap_host: '', imap_port: 993, imap_secure: true, imap_user: '', imap_pass: '',
  smtp_host: '', smtp_port: 587, smtp_secure: true, smtp_user: '', smtp_pass: ''
};

function TabBar({ tabs, active, onChange }) {
  return (
    <div className="flex gap-1 border-b border-border-soft">
      {tabs.map(t => (
        <button
          key={t.key}
          onClick={() => onChange(t.key)}
          className={`px-3.5 py-2 text-[13px] font-medium border-b-2 -mb-px transition-colors ${
            active === t.key ? 'border-accent text-accent' : 'border-transparent text-muted hover:text-text'
          }`}
        >
          {t.label}
        </button>
      ))}
    </div>
  );
}

export default function Email() {
  const [tab, setTab] = useState('inbox');

  // Inbox
  const [messages, setMessages] = useState(null);
  const [msgError, setMsgError] = useState(null);
  const [syncing, setSyncing] = useState(false);
  const [banner, setBanner] = useState(null); // { type: 'green'|'red', text }
  const [composeOpen, setComposeOpen] = useState(false);
  const [compose, setCompose] = useState(EMPTY_COMPOSE);
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState(null);
  const [detail, setDetail] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailError, setDetailError] = useState(null);

  // Accounts
  const [accounts, setAccounts] = useState(null);
  const [accError, setAccError] = useState(null);
  const [accModal, setAccModal] = useState(false);
  const [editAcc, setEditAcc] = useState(null);
  const [accForm, setAccForm] = useState(EMPTY_ACCOUNT);
  const [savingAcc, setSavingAcc] = useState(false);
  const [accSaveError, setAccSaveError] = useState(null);

  const loadMessages = () => {
    setMsgError(null);
    api.get('/email/messages').then(setMessages).catch(setMsgError);
  };
  const loadAccounts = () => {
    setAccError(null);
    api.get('/email/accounts').then(setAccounts).catch(setAccError);
  };
  useEffect(() => { loadMessages(); loadAccounts(); }, []);

  const showBanner = (type, text) => {
    setBanner({ type, text });
    setTimeout(() => setBanner(null), 6000);
  };

  // ---- Sync ----
  const sync = async () => {
    setSyncing(true);
    setBanner(null);
    try {
      await api.post('/email/sync');
      showBanner('green', 'Inbox gesynchroniseerd');
      loadMessages();
    } catch (err) {
      showBanner('red', err.message || String(err));
    } finally {
      setSyncing(false);
    }
  };

  // ---- Compose ----
  const openCompose = () => {
    setCompose(EMPTY_COMPOSE);
    setSendError(null);
    setComposeOpen(true);
  };
  const sendMail = async (e) => {
    e.preventDefault();
    setSending(true);
    setSendError(null);
    try {
      await api.post('/email/send', compose);
      setComposeOpen(false);
      showBanner('green', 'E-mail verzonden');
    } catch (err) {
      setSendError(err);
    } finally {
      setSending(false);
    }
  };

  // ---- Detail ----
  const openDetail = (m) => {
    setDetail(null);
    setDetailError(null);
    setDetailLoading(true);
    api.get(`/email/messages/${m.id}`)
      .then(res => { setDetail(res); loadMessages(); })
      .catch(setDetailError)
      .finally(() => setDetailLoading(false));
  };
  const closeDetail = () => {
    setDetail(null);
    setDetailError(null);
    setDetailLoading(false);
  };

  // ---- Accounts ----
  const openAccNew = () => {
    setEditAcc(null);
    setAccForm(EMPTY_ACCOUNT);
    setAccSaveError(null);
    setAccModal(true);
  };
  const openAccEdit = (a) => {
    setEditAcc(a);
    setAccForm({
      email: a.email || '', name: a.name || '', imap_host: a.imap_host || '', imap_port: a.imap_port || 993,
      imap_secure: !!a.imap_secure, imap_user: a.imap_user || '', imap_pass: '',
      smtp_host: a.smtp_host || '', smtp_port: a.smtp_port || 587, smtp_secure: !!a.smtp_secure,
      smtp_user: a.smtp_user || '', smtp_pass: ''
    });
    setAccSaveError(null);
    setAccModal(true);
  };
  const saveAcc = async (e) => {
    e.preventDefault();
    setSavingAcc(true);
    setAccSaveError(null);
    try {
      await api.post('/email/accounts', { ...accForm, id: editAcc ? editAcc.id : undefined });
      setAccModal(false);
      loadAccounts();
    } catch (err) {
      setAccSaveError(err);
    } finally {
      setSavingAcc(false);
    }
  };

  const detailOpen = detailLoading || !!detail || !!detailError;

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold tracking-tight">E-mail</h1>
          <p className="text-[13px] text-muted mt-0.5">Postvak IN en e-mailaccounts</p>
        </div>
        {tab === 'inbox' ? (
          <div className="flex items-center gap-2">
            <Btn variant="secondary" onClick={sync} loading={syncing}>
              <RefreshCw className="w-4 h-4" /> Synchroniseren
            </Btn>
            <Btn onClick={openCompose}><MailPlus className="w-4 h-4" /> Nieuwe e-mail</Btn>
          </div>
        ) : (
          <Btn onClick={openAccNew}><MailPlus className="w-4 h-4" /> Account toevoegen</Btn>
        )}
      </div>

      {banner && (
        <div className={`rounded-lg px-4 py-3 text-[13px] border ${
          banner.type === 'green' ? 'bg-green/10 border-green/30 text-green' : 'bg-red/10 border-red/30 text-red'
        }`}>
          {banner.text}
        </div>
      )}

      <TabBar
        tabs={[{ key: 'inbox', label: 'Postvak IN' }, { key: 'accounts', label: 'Accounts' }]}
        active={tab}
        onChange={setTab}
      />

      {tab === 'inbox' && (
        <Card padding={false}>
          <div className="p-4">
            {msgError ? <ErrorBox error={msgError} onRetry={loadMessages} /> : !messages ? <Spinner /> : (
              <Table
                columns={[
                  {
                    label: '', className: 'w-6',
                    render: m => !m.seen ? <span className="block w-2 h-2 rounded-full bg-blue" title="Ongelezen" /> : null
                  },
                  { label: 'Van', render: m => <span className={!m.seen ? 'font-semibold' : ''}>{m.from_name || m.from_addr || '-'}</span> },
                  {
                    label: 'Onderwerp',
                    render: m => (
                      <button onClick={() => openDetail(m)} className={`text-left text-accent hover:underline ${!m.seen ? 'font-semibold' : ''}`}>
                        {m.subject || '(geen onderwerp)'}
                      </button>
                    )
                  },
                  { label: 'Datum', render: m => <span className="text-muted">{fmt.datetime(m.date)}</span> },
                  { label: 'Account', render: m => <span className="text-muted">{m.account_email}</span> }
                ]}
                rows={messages}
                keyFn={m => m.id}
                empty={
                  <div className="flex flex-col items-center py-10 text-muted">
                    <Inbox className="w-8 h-8 mb-2" />
                    <div className="text-[13px]">Geen berichten — synchroniseer je inbox</div>
                  </div>
                }
              />
            )}
          </div>
        </Card>
      )}

      {tab === 'accounts' && (
        <Card padding={false}>
          <div className="p-4">
            {accError ? <ErrorBox error={accError} onRetry={loadAccounts} /> : !accounts ? <Spinner /> : (
              <Table
                columns={[
                  { label: 'Email', render: a => <span className="font-medium flex items-center gap-2"><Mail className="w-3.5 h-3.5 text-muted" />{a.email}</span> },
                  { label: 'IMAP', render: a => <span className="text-muted">{a.imap_host}:{a.imap_port}</span> },
                  { label: 'SMTP', render: a => <span className="text-muted">{a.smtp_host}:{a.smtp_port}</span> },
                  { label: 'Actief', render: a => <Badge color={a.active ? 'green' : 'muted'}>{a.active ? 'Actief' : 'Inactief'}</Badge> }
                ]}
                rows={accounts}
                keyFn={a => a.id}
                onRowClick={openAccEdit}
                empty={<div className="text-center text-muted text-[13px] py-8">Nog geen accounts geconfigureerd</div>}
              />
            )}
          </div>
        </Card>
      )}

      {/* Compose-modal */}
      <Modal open={composeOpen} onClose={() => setComposeOpen(false)} title="Nieuwe e-mail">
        <form onSubmit={sendMail} className="space-y-3">
          {sendError && <ErrorBox error={sendError} />}
          <Field label="Aan *">
            <input className={inputCls} value={compose.to} onChange={e => setCompose({ ...compose, to: e.target.value })} required />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="CC">
              <input className={inputCls} value={compose.cc} onChange={e => setCompose({ ...compose, cc: e.target.value })} />
            </Field>
            <Field label="BCC">
              <input className={inputCls} value={compose.bcc} onChange={e => setCompose({ ...compose, bcc: e.target.value })} />
            </Field>
          </div>
          <Field label="Onderwerp *">
            <input className={inputCls} value={compose.subject} onChange={e => setCompose({ ...compose, subject: e.target.value })} required />
          </Field>
          <Field label="Bericht">
            <textarea rows={8} className={inputCls} value={compose.text} onChange={e => setCompose({ ...compose, text: e.target.value })} />
          </Field>
          <div className="flex justify-end gap-2 pt-1">
            <Btn variant="secondary" type="button" onClick={() => setComposeOpen(false)}>Annuleren</Btn>
            <Btn type="submit" loading={sending}>Verzenden</Btn>
          </div>
        </form>
      </Modal>

      {/* Bericht-detail-modal */}
      <Modal open={detailOpen} onClose={closeDetail} title={detail ? (detail.subject || '(geen onderwerp)') : 'Bericht laden'} wide>
        {detailLoading && <Spinner />}
        {detailError && <ErrorBox error={detailError} />}
        {detail && (
          <div className="space-y-3">
            <div className="text-[12px] text-muted space-y-0.5">
              <div>Van: <span className="text-text">{detail.from_name || detail.from_addr}</span></div>
              <div>Datum: <span className="text-text">{fmt.datetime(detail.date)}</span></div>
              <div>Account: <span className="text-text">{detail.account_email}</span></div>
            </div>
            <div className="border-t border-border-soft pt-3 text-[13px] whitespace-pre-wrap max-h-[50vh] overflow-y-auto">
              {detail.body_text || '(geen inhoud)'}
            </div>
            <div className="flex justify-end pt-1">
              <Btn variant="secondary" onClick={closeDetail}>Sluiten</Btn>
            </div>
          </div>
        )}
      </Modal>

      {/* Account-modal */}
      <Modal open={accModal} onClose={() => setAccModal(false)} title={editAcc ? 'Account bewerken' : 'Account toevoegen'} wide>
        <form onSubmit={saveAcc} className="space-y-3">
          {accSaveError && <ErrorBox error={accSaveError} />}
          <div className="grid grid-cols-2 gap-3">
            <Field label="E-mailadres *">
              <input type="email" className={inputCls} value={accForm.email} onChange={e => setAccForm({ ...accForm, email: e.target.value })} required />
            </Field>
            <Field label="Weergavenaam">
              <input className={inputCls} value={accForm.name} onChange={e => setAccForm({ ...accForm, name: e.target.value })} />
            </Field>
          </div>
          <div className="text-[12px] text-muted font-medium pt-1">IMAP (inkomend)</div>
          <div className="grid grid-cols-3 gap-3">
            <Field label="IMAP host *" className="col-span-2">
              <input className={inputCls} value={accForm.imap_host} onChange={e => setAccForm({ ...accForm, imap_host: e.target.value })} required />
            </Field>
            <Field label="Poort">
              <input type="number" className={inputCls} value={accForm.imap_port} onChange={e => setAccForm({ ...accForm, imap_port: e.target.value })} />
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="IMAP gebruiker *">
              <input className={inputCls} value={accForm.imap_user} onChange={e => setAccForm({ ...accForm, imap_user: e.target.value })} required />
            </Field>
            <Field label="IMAP wachtwoord *">
              <input
                type="password"
                className={inputCls}
                value={accForm.imap_pass}
                onChange={e => setAccForm({ ...accForm, imap_pass: e.target.value })}
                placeholder={editAcc ? 'Leeg laten om te behouden' : ''}
                required={!editAcc}
              />
            </Field>
          </div>
          <label className="flex items-center gap-2 text-[13px] cursor-pointer">
            <input type="checkbox" checked={accForm.imap_secure} onChange={e => setAccForm({ ...accForm, imap_secure: e.target.checked })} className="accent-[#00d4ff]" />
            IMAP via SSL/TLS
          </label>
          <div className="text-[12px] text-muted font-medium pt-1">SMTP (uitgaand)</div>
          <div className="grid grid-cols-3 gap-3">
            <Field label="SMTP host" className="col-span-2">
              <input className={inputCls} value={accForm.smtp_host} onChange={e => setAccForm({ ...accForm, smtp_host: e.target.value })} placeholder="Standaard = IMAP host" />
            </Field>
            <Field label="Poort">
              <input type="number" className={inputCls} value={accForm.smtp_port} onChange={e => setAccForm({ ...accForm, smtp_port: e.target.value })} />
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="SMTP gebruiker">
              <input className={inputCls} value={accForm.smtp_user} onChange={e => setAccForm({ ...accForm, smtp_user: e.target.value })} placeholder="Standaard = IMAP gebruiker" />
            </Field>
            <Field label="SMTP wachtwoord">
              <input
                type="password"
                className={inputCls}
                value={accForm.smtp_pass}
                onChange={e => setAccForm({ ...accForm, smtp_pass: e.target.value })}
                placeholder={editAcc ? 'Leeg laten om te behouden' : 'Standaard = IMAP wachtwoord'}
              />
            </Field>
          </div>
          <label className="flex items-center gap-2 text-[13px] cursor-pointer">
            <input type="checkbox" checked={accForm.smtp_secure} onChange={e => setAccForm({ ...accForm, smtp_secure: e.target.checked })} className="accent-[#00d4ff]" />
            SMTP via SSL/TLS
          </label>
          <div className="flex justify-end gap-2 pt-1">
            <Btn variant="secondary" type="button" onClick={() => setAccModal(false)}>Annuleren</Btn>
            <Btn type="submit" loading={savingAcc}>Opslaan</Btn>
          </div>
        </form>
      </Modal>
    </div>
  );
}
