import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, Search, Pencil, Trash2, Users } from 'lucide-react';
import { api, qs, fmt } from '../api';
import { Card, Btn, Field, inputCls, Modal, Spinner, ErrorBox, Table, StatusBadge, EmptyState } from '../components/ui';

const STATUS_LABELS = { lead: 'Lead', active: 'Actief', paused: 'Gepauzeerd', archived: 'Gearchiveerd' };

const FILTERS = [
  { key: '', label: 'Alle' },
  { key: 'lead', label: 'Leads' },
  { key: 'active', label: 'Actief' },
  { key: 'paused', label: 'Gepauzeerd' },
  { key: 'archived', label: 'Gearchiveerd' }
];

const EMPTY_FORM = {
  name: '', industry: '', website: '', contact_name: '', contact_email: '',
  contact_phone: '', status: 'lead', source: '', notes: ''
};

function ClientFormModal({ open, onClose, client, onSaved, onDelete }) {
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open) return;
    setError(null);
    setForm(client ? {
      name: client.name || '',
      industry: client.industry || '',
      website: client.website || '',
      contact_name: client.contact_name || '',
      contact_email: client.contact_email || '',
      contact_phone: client.contact_phone || '',
      status: client.status || 'lead',
      source: client.source || '',
      notes: client.notes || ''
    } : EMPTY_FORM);
  }, [open, client]);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    try {
      if (client) await api.put(`/clients/${client.id}`, form);
      else await api.post('/clients', form);
      onSaved();
    } catch (err) {
      setError(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title={client ? 'Cliënt bewerken' : 'Nieuwe cliënt'} wide>
      <form onSubmit={submit} className="space-y-3">
        <ErrorBox error={error} />
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <Field label="Bedrijfsnaam *" className="md:col-span-2">
            <input className={inputCls} value={form.name} onChange={set('name')} required autoFocus />
          </Field>
          <Field label="Branche">
            <input className={inputCls} value={form.industry} onChange={set('industry')} />
          </Field>
          <Field label="Website">
            <input className={inputCls} value={form.website} onChange={set('website')} placeholder="https://..." />
          </Field>
          <Field label="Contactpersoon">
            <input className={inputCls} value={form.contact_name} onChange={set('contact_name')} />
          </Field>
          <Field label="E-mail">
            <input type="email" className={inputCls} value={form.contact_email} onChange={set('contact_email')} />
          </Field>
          <Field label="Telefoon">
            <input className={inputCls} value={form.contact_phone} onChange={set('contact_phone')} />
          </Field>
          <Field label="Status">
            <select className={inputCls} value={form.status} onChange={set('status')}>
              {Object.entries(STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
          </Field>
          <Field label="Bron" className="md:col-span-2">
            <input className={inputCls} value={form.source} onChange={set('source')} placeholder="Bijv. referral, website, netwerk" />
          </Field>
          <Field label="Notities" className="md:col-span-2">
            <textarea className={inputCls} rows={3} value={form.notes} onChange={set('notes')} />
          </Field>
        </div>
        <div className="flex items-center justify-between gap-2 pt-1">
          <div>
            {client && onDelete && (
              <Btn type="button" variant="danger" onClick={onDelete}>
                <Trash2 className="w-3.5 h-3.5" /> Verwijderen
              </Btn>
            )}
          </div>
          <div className="flex gap-2">
            <Btn type="button" variant="secondary" onClick={onClose}>Annuleren</Btn>
            <Btn type="submit" loading={saving}>{client ? 'Opslaan' : 'Aanmaken'}</Btn>
          </div>
        </div>
      </form>
    </Modal>
  );
}

export default function Clients() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [status, setStatus] = useState('');
  const [search, setSearch] = useState('');
  const [activeSearch, setActiveSearch] = useState('');
  const [modal, setModal] = useState({ open: false, client: null });

  const load = () => {
    setError(null);
    api.get('/clients' + qs({ status, search: activeSearch })).then(setData).catch(setError);
  };
  useEffect(load, [status, activeSearch]);

  const submitSearch = (e) => {
    e.preventDefault();
    setActiveSearch(search.trim());
  };

  const closeModal = () => setModal({ open: false, client: null });

  const remove = async () => {
    const c = modal.client;
    if (!c) return;
    if (!window.confirm(`Cliënt "${c.name}" verwijderen? Dit kan niet ongedaan worden gemaakt.`)) return;
    try {
      await api.del(`/clients/${c.id}`);
      closeModal();
      load();
    } catch (err) {
      setError(err);
    }
  };

  return (
    <div className="space-y-4 fade-in">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Cliënten</h1>
          <p className="text-[13px] text-muted mt-0.5">Beheer je klantrelaties</p>
        </div>
        <Btn onClick={() => setModal({ open: true, client: null })}>
          <Plus className="w-4 h-4" /> Nieuwe cliënt
        </Btn>
      </div>

      <div className="flex items-center gap-3 flex-wrap">
        <form onSubmit={submitSearch} className="flex gap-2">
          <input
            className={inputCls + ' w-64'}
            placeholder="Zoeken op naam, contact of branche..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
          <Btn type="submit" variant="secondary"><Search className="w-4 h-4" /> Zoeken</Btn>
        </form>
        <div className="flex gap-1 flex-wrap">
          {FILTERS.map((f) => (
            <button
              key={f.key}
              onClick={() => setStatus(f.key)}
              className={`px-3 py-1.5 rounded-lg text-[12px] transition-colors ${status === f.key ? 'bg-accent-soft text-accent font-medium' : 'text-muted hover:text-text hover:bg-card'}`}
            >
              {f.label}
            </button>
          ))}
        </div>
      </div>

      {error && <ErrorBox error={error} onRetry={load} />}
      {!data && !error && <Spinner />}

      {data && (
        <Card padding={false}>
          <div className="p-4">
            <Table
              columns={[
                {
                  label: 'Naam',
                  render: (c) => (
                    <Link to={`/clients/${c.id}`} className="font-medium text-text hover:text-accent transition-colors">
                      {c.name}
                    </Link>
                  )
                },
                { label: 'Contactpersoon', render: (c) => c.contact_name || <span className="text-muted">-</span> },
                { label: 'E-mail', render: (c) => c.contact_email || <span className="text-muted">-</span> },
                { label: 'Branche', render: (c) => c.industry || <span className="text-muted">-</span> },
                { label: 'Status', render: (c) => <StatusBadge status={c.status} labels={STATUS_LABELS} /> },
                { label: 'Engagements', render: (c) => c.engagement_count },
                { label: 'Laatst bijgewerkt', render: (c) => <span className="text-muted">{fmt.date(c.updated_at)}</span> },
                {
                  label: '',
                  render: (c) => (
                    <div className="flex items-center justify-end">
                      <button
                        onClick={() => setModal({ open: true, client: c })}
                        className="p-1.5 rounded-md text-muted hover:text-text hover:bg-bg-soft"
                        title="Bewerken"
                      >
                        <Pencil className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  )
                }
              ]}
              rows={data}
              keyFn={(c) => c.id}
              empty={<EmptyState icon={Users} title="Geen cliënten gevonden" hint="Pas de filters aan of voeg een nieuwe cliënt toe." />}
            />
          </div>
        </Card>
      )}

      <ClientFormModal
        open={modal.open}
        client={modal.client}
        onClose={closeModal}
        onSaved={() => { closeModal(); load(); }}
        onDelete={remove}
      />
    </div>
  );
}
