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

export const TYPE_LABELS = {
  assessment: 'Assessment', architecture: 'Architectuur', implementation: 'Implementatie',
  monitoring: 'Monitoring', consulting: 'Consulting', training: 'Training'
};
export const ENG_STATUS_LABELS = { planned: 'Gepland', in_progress: 'Lopend', completed: 'Afgerond', on_hold: 'On hold' };

const selectCls =
  'bg-bg-soft border border-border rounded-lg px-3 py-2 text-[13px] focus:outline-none focus:border-accent/60 transition-colors';

const EMPTY_FORM = { client_id: '', type: 'assessment', title: '', description: '', start_date: '', end_date: '' };

export function EngagementFormModal({ open, onClose, clients = [], clientId, onSaved }) {
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open) return;
    setError(null);
    setForm({ ...EMPTY_FORM, client_id: clientId ? String(clientId) : '' });
  }, [open, clientId]);

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

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    try {
      await api.post('/engagements', { ...form, client_id: clientId || form.client_id });
      onSaved();
    } catch (err) {
      setError(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Nieuw engagement">
      <form onSubmit={submit} className="space-y-3">
        <ErrorBox error={error} />
        {!clientId && (
          <Field label="Cliënt *">
            <select className={inputCls} value={form.client_id} onChange={set('client_id')} required>
              <option value="">— Kies een cliënt —</option>
              {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </Field>
        )}
        <Field label="Type *">
          <select className={inputCls} value={form.type} onChange={set('type')} required>
            {Object.entries(TYPE_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
        </Field>
        <Field label="Titel *">
          <input className={inputCls} value={form.title} onChange={set('title')} required autoFocus />
        </Field>
        <Field label="Omschrijving">
          <textarea className={inputCls} rows={3} value={form.description} onChange={set('description')} />
        </Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Startdatum">
            <input type="date" className={inputCls} value={form.start_date} onChange={set('start_date')} />
          </Field>
          <Field label="Einddatum">
            <input type="date" className={inputCls} value={form.end_date} onChange={set('end_date')} />
          </Field>
        </div>
        <div className="flex justify-end gap-2 pt-1">
          <Btn type="button" variant="secondary" onClick={onClose}>Annuleren</Btn>
          <Btn type="submit" loading={saving}>Aanmaken</Btn>
        </div>
      </form>
    </Modal>
  );
}

export default function Engagements() {
  const [data, setData] = useState(null);
  const [clients, setClients] = useState([]);
  const [error, setError] = useState(null);
  const [filters, setFilters] = useState({ type: '', status: '', client_id: '' });
  const [modalOpen, setModalOpen] = useState(false);

  const load = () => {
    setError(null);
    api.get('/engagements' + qs(filters)).then(setData).catch(setError);
  };
  useEffect(load, [filters.type, filters.status, filters.client_id]);
  useEffect(() => {
    api.get('/clients').then(setClients).catch(() => { /* filter-opties zijn optioneel */ });
  }, []);

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

  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">Engagements</h1>
          <p className="text-[13px] text-muted mt-0.5">Alle opdrachten en projecten</p>
        </div>
        <Btn onClick={() => setModalOpen(true)}>
          <Plus className="w-4 h-4" /> Nieuw engagement
        </Btn>
      </div>

      <div className="flex items-center gap-2 flex-wrap">
        <select className={selectCls} value={filters.type} onChange={setFilter('type')}>
          <option value="">Alle types</option>
          {Object.entries(TYPE_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        <select className={selectCls} value={filters.status} onChange={setFilter('status')}>
          <option value="">Alle statussen</option>
          {Object.entries(ENG_STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        <select className={selectCls} value={filters.client_id} onChange={setFilter('client_id')}>
          <option value="">Alle cliënten</option>
          {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
      </div>

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

      {data && (
        <Card padding={false}>
          <div className="p-4">
            <Table
              columns={[
                {
                  label: 'Titel',
                  render: (e) => (
                    <Link to={`/engagements/${e.id}`} className="font-medium text-text hover:text-accent transition-colors">
                      {e.title}
                    </Link>
                  )
                },
                {
                  label: 'Cliënt',
                  render: (e) => (
                    <Link to={`/clients/${e.client_id}`} className="text-muted hover:text-accent transition-colors">
                      {e.client_name}
                    </Link>
                  )
                },
                { label: 'Type', render: (e) => TYPE_LABELS[e.type] || e.type },
                { label: 'Status', render: (e) => <StatusBadge status={e.status} labels={ENG_STATUS_LABELS} /> },
                { label: 'Taken', render: (e) => e.task_count },
                { label: 'Start', render: (e) => <span className="text-muted">{fmt.date(e.start_date)}</span> },
                { label: 'Eind', render: (e) => <span className="text-muted">{fmt.date(e.end_date)}</span> }
              ]}
              rows={data}
              keyFn={(e) => e.id}
              empty={<EmptyState icon={Briefcase} title="Geen engagements gevonden" hint="Pas de filters aan of maak een nieuw engagement aan." />}
            />
          </div>
        </Card>
      )}

      <EngagementFormModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        clients={clients}
        onSaved={() => { setModalOpen(false); load(); }}
      />
    </div>
  );
}
