import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Pencil, Trash2, Plus } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Btn, Field, inputCls, Modal, Spinner, ErrorBox, Table, StatusBadge, Badge } from '../components/ui';
import { TYPE_LABELS, ENG_STATUS_LABELS } from './Engagements';
import { TASK_STATUS_LABELS, PRIORITY_LABELS } from './Tasks';

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 selectSmCls =
  'bg-bg-soft border border-border rounded-lg px-2 py-1 text-[12px] focus:outline-none focus:border-accent/60 transition-colors shrink-0';

const EMPTY_EDIT = { type: 'assessment', title: '', description: '', start_date: '', end_date: '', status: 'planned', outcome: '' };

function EditEngagementModal({ open, onClose, engagement, onSaved }) {
  const [form, setForm] = useState(EMPTY_EDIT);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open || !engagement) return;
    setError(null);
    setForm({
      type: engagement.type || 'assessment',
      title: engagement.title || '',
      description: engagement.description || '',
      start_date: engagement.start_date || '',
      end_date: engagement.end_date || '',
      status: engagement.status || 'planned',
      outcome: engagement.outcome || ''
    });
  }, [open, engagement]);

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

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

  return (
    <Modal open={open} onClose={onClose} title="Engagement bewerken">
      <form onSubmit={submit} className="space-y-3">
        <ErrorBox error={error} />
        <div className="grid grid-cols-2 gap-3">
          <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="Status">
            <select className={inputCls} value={form.status} onChange={set('status')}>
              {Object.entries(ENG_STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
          </Field>
        </div>
        <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>
        <Field label="Resultaat (outcome)">
          <textarea className={inputCls} rows={2} value={form.outcome} onChange={set('outcome')} />
        </Field>
        <div className="flex justify-end gap-2 pt-1">
          <Btn type="button" variant="secondary" onClick={onClose}>Annuleren</Btn>
          <Btn type="submit" loading={saving}>Opslaan</Btn>
        </div>
      </form>
    </Modal>
  );
}

function TaskFormModal({ open, onClose, engagementId, onSaved }) {
  const EMPTY = { title: '', priority: 'medium', due_date: '' };
  const [form, setForm] = useState(EMPTY);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open) return;
    setError(null);
    setForm(EMPTY);
  }, [open]);

  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('/tasks', { ...form, engagement_id: engagementId, due_date: form.due_date || null });
      onSaved();
    } catch (err) {
      setError(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Taak toevoegen">
      <form onSubmit={submit} className="space-y-3">
        <ErrorBox error={error} />
        <Field label="Titel *">
          <input className={inputCls} value={form.title} onChange={set('title')} required autoFocus />
        </Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Prioriteit">
            <select className={inputCls} value={form.priority} onChange={set('priority')}>
              {Object.entries(PRIORITY_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
          </Field>
          <Field label="Deadline">
            <input type="date" className={inputCls} value={form.due_date} onChange={set('due_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 EngagementDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [editOpen, setEditOpen] = useState(false);
  const [taskModalOpen, setTaskModalOpen] = useState(false);

  const load = () => {
    setError(null);
    api.get(`/engagements/${id}`).then(setData).catch(setError);
  };
  useEffect(load, [id]);

  if (!data) {
    return error ? <ErrorBox error={error} onRetry={load} /> : <Spinner />;
  }

  const { engagement, tasks, timeEntries } = data;

  const changeStatus = async (e) => {
    try {
      await api.post(`/engagements/${id}/status`, { status: e.target.value });
      load();
    } catch (err) {
      setError(err);
    }
  };

  const remove = async () => {
    if (!window.confirm(`Engagement "${engagement.title}" verwijderen? Dit kan niet ongedaan worden gemaakt.`)) return;
    try {
      await api.del(`/engagements/${id}`);
      navigate('/engagements');
    } catch (err) {
      setError(err);
    }
  };

  const setTaskStatus = async (taskId, status) => {
    try {
      await api.post(`/tasks/${taskId}/status`, { status });
      load();
    } catch (err) {
      setError(err);
    }
  };

  const removeTask = async (t) => {
    if (!window.confirm(`Taak "${t.title}" verwijderen?`)) return;
    try {
      await api.del(`/tasks/${t.id}`);
      load();
    } catch (err) {
      setError(err);
    }
  };

  return (
    <div className="space-y-4 fade-in">
      {error && <ErrorBox error={error} onRetry={load} />}

      {/* Header */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div className="min-w-0">
          <div className="flex items-center gap-3 flex-wrap">
            <h1 className="text-xl font-bold tracking-tight">{engagement.title}</h1>
            <StatusBadge status={engagement.status} labels={ENG_STATUS_LABELS} />
            <Badge color="accent">{TYPE_LABELS[engagement.type] || engagement.type}</Badge>
          </div>
          <div className="flex items-center gap-3 mt-1.5 text-[13px] text-muted flex-wrap">
            <Link to={`/clients/${engagement.client_id}`} className="text-accent hover:underline">
              {engagement.client_name}
            </Link>
            <span>{fmt.date(engagement.start_date)} – {fmt.date(engagement.end_date)}</span>
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0 flex-wrap">
          <select className={selectCls} value={engagement.status} onChange={changeStatus} title="Status wijzigen">
            {Object.entries(ENG_STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
          <Btn variant="secondary" onClick={() => setEditOpen(true)}>
            <Pencil className="w-3.5 h-3.5" /> Bewerken
          </Btn>
          <Btn variant="danger" onClick={remove}>
            <Trash2 className="w-3.5 h-3.5" /> Verwijderen
          </Btn>
        </div>
      </div>

      {(engagement.description || engagement.outcome) && (
        <Card title="Details">
          {engagement.description && <p className="text-[13px] whitespace-pre-wrap">{engagement.description}</p>}
          {engagement.outcome && (
            <div className={engagement.description ? 'mt-3 pt-3 border-t border-border-soft' : ''}>
              <div className="text-[12px] text-muted mb-1">Resultaat</div>
              <p className="text-[13px] whitespace-pre-wrap">{engagement.outcome}</p>
            </div>
          )}
        </Card>
      )}

      {/* Taken */}
      <Card
        title={`Taken (${tasks.length})`}
        actions={<Btn size="sm" onClick={() => setTaskModalOpen(true)}><Plus className="w-3.5 h-3.5" /> Taak toevoegen</Btn>}
      >
        {tasks.length === 0 ? (
          <div className="text-muted text-[13px] py-4 text-center">Nog geen taken</div>
        ) : (
          <div className="space-y-1.5">
            {tasks.map((t) => (
              <div key={t.id} className="flex items-center gap-3 px-2.5 py-2 rounded-lg hover:bg-card-hover transition-colors">
                <select
                  className={selectSmCls}
                  value={t.status}
                  onChange={(e) => setTaskStatus(t.id, e.target.value)}
                >
                  {Object.entries(TASK_STATUS_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                </select>
                <div className="min-w-0 flex-1">
                  <div className="text-[13px] font-medium truncate">{t.title}</div>
                  {t.due_date && <div className="text-[11px] text-muted">Deadline: {fmt.date(t.due_date)}</div>}
                </div>
                <StatusBadge status={t.priority} labels={PRIORITY_LABELS} />
                <button
                  onClick={() => removeTask(t)}
                  className="p-1.5 rounded-md text-muted hover:text-red hover:bg-bg-soft shrink-0"
                  title="Verwijderen"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* Uren */}
      <Card title={`Uren (${timeEntries.length})`}>
        <Table
          columns={[
            { label: 'Datum', render: (t) => fmt.date(t.date) },
            { label: 'Gebruiker', render: (t) => t.username || <span className="text-muted">-</span> },
            { label: 'Uren', render: (t) => fmt.hours(t.hours) },
            { label: 'Omschrijving', render: (t) => t.description || <span className="text-muted">-</span> },
            { label: 'Facturabel', render: (t) => <Badge color={t.billable ? 'green' : 'muted'}>{t.billable ? 'Ja' : 'Nee'}</Badge> }
          ]}
          rows={timeEntries}
          keyFn={(t) => t.id}
          empty={<div className="text-muted text-[13px] py-4 text-center">Nog geen uren geregistreerd</div>}
        />
      </Card>

      <EditEngagementModal
        open={editOpen}
        engagement={engagement}
        onClose={() => setEditOpen(false)}
        onSaved={() => { setEditOpen(false); load(); }}
      />
      <TaskFormModal
        open={taskModalOpen}
        engagementId={engagement.id}
        onClose={() => setTaskModalOpen(false)}
        onSaved={() => { setTaskModalOpen(false); load(); }}
      />
    </div>
  );
}
