import { useEffect, useState } from 'react';
import { Trash2, Workflow, ArrowRight } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Badge, Btn, Modal, Spinner, ErrorBox, Table } from '../components/ui';

const TYPE_LABELS = {
  data_architecture: 'Data-architectuur',
  network_topology: 'Netwerk-topologie',
  system_architecture: 'Systeem-architectuur',
  application_flow: 'Applicatie-flow',
  application_landscape: 'Applicatie-landscape'
};
const TYPE_COLORS = {
  data_architecture: 'accent',
  network_topology: 'green',
  system_architecture: 'purple',
  application_flow: 'blue',
  application_landscape: 'pink'
};

function nodeLabel(n) {
  return n.data?.label || n.label || n.name || n.id;
}

export default function Diagrams() {
  const [diagrams, setDiagrams] = useState(null);
  const [error, setError] = useState(null);
  const [detail, setDetail] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailError, setDetailError] = useState(null);
  const [deleting, setDeleting] = useState(false);

  const load = () => {
    setError(null);
    api.get('/diagrams').then(setDiagrams).catch(setError);
  };
  useEffect(load, []);

  const openDetail = (row) => {
    setDetail(null);
    setDetailError(null);
    setDetailLoading(true);
    api.get(`/diagrams/${row.id}`)
      .then(setDetail)
      .catch(setDetailError)
      .finally(() => setDetailLoading(false));
  };

  const closeDetail = () => {
    setDetail(null);
    setDetailError(null);
    setDetailLoading(false);
  };

  const deleteDiagram = async () => {
    if (!detail) return;
    if (!window.confirm(`Diagram "${detail.name}" verwijderen?`)) return;
    setDeleting(true);
    setDetailError(null);
    try {
      await api.del(`/diagrams/${detail.id}`);
      closeDetail();
      load();
    } catch (err) {
      setDetailError(err);
    } finally {
      setDeleting(false);
    }
  };

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

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

  return (
    <div className="space-y-5 fade-in">
      <div>
        <h1 className="text-xl font-bold tracking-tight">Diagrammen</h1>
        <p className="text-[13px] text-muted mt-0.5">
          Bewerken van diagrammen kan in de{' '}
          <a href="/architecture" className="text-accent underline">klassieke editor</a>
        </p>
      </div>

      <Card padding={false}>
        <div className="p-4">
          <Table
            columns={[
              { label: 'Naam', render: d => <span className="font-medium flex items-center gap-2"><Workflow className="w-3.5 h-3.5 text-muted" />{d.name}</span> },
              { label: 'Cliënt', key: 'client_name' },
              { label: 'Type', render: d => <Badge color={TYPE_COLORS[d.diagram_type] || 'muted'}>{TYPE_LABELS[d.diagram_type] || d.diagram_type}</Badge> },
              { label: 'Beschrijving', render: d => <span className="text-muted block max-w-xs truncate">{d.description || '-'}</span> },
              { label: 'Bijgewerkt', render: d => <span className="text-muted">{fmt.datetime(d.updated_at)}</span> }
            ]}
            rows={diagrams}
            keyFn={d => d.id}
            onRowClick={openDetail}
            empty={<div className="text-center text-muted text-[13px] py-8">Nog geen diagrammen</div>}
          />
        </div>
      </Card>

      <Modal open={modalOpen} onClose={closeDetail} title={detail ? detail.name : 'Diagram laden'} wide>
        {detailLoading && <Spinner />}
        {detailError && <ErrorBox error={detailError} />}
        {detail && (
          <div className="space-y-4">
            <div className="flex items-center gap-2 flex-wrap text-[12px] text-muted">
              <Badge color={TYPE_COLORS[detail.diagram_type] || 'muted'}>{TYPE_LABELS[detail.diagram_type] || detail.diagram_type}</Badge>
              <span>Bijgewerkt: {fmt.datetime(detail.updated_at)}</span>
            </div>
            {detail.description && <p className="text-[13px] text-muted">{detail.description}</p>}

            <div>
              <h3 className="text-[13px] font-semibold mb-2">Nodes ({detail.nodes.length})</h3>
              {detail.nodes.length === 0 ? (
                <div className="text-muted text-[13px]">Geen nodes</div>
              ) : (
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  {detail.nodes.map((n, i) => (
                    <div key={n.id || i} className="bg-bg-soft border border-border-soft rounded-lg px-3 py-2">
                      <div className="text-[13px] font-medium truncate">{nodeLabel(n)}</div>
                      {(n.type || n.data?.type) && (
                        <Badge color="blue" className="mt-1">{n.data?.type || n.type}</Badge>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div>
              <h3 className="text-[13px] font-semibold mb-2">Verbindingen ({detail.edges.length})</h3>
              {detail.edges.length === 0 ? (
                <div className="text-muted text-[13px]">Geen verbindingen</div>
              ) : (
                <div className="space-y-1">
                  {detail.edges.map((e, i) => (
                    <div key={e.id || i} className="flex items-center gap-2 text-[12px] text-muted bg-bg-soft border border-border-soft rounded-lg px-3 py-1.5">
                      <span className="text-text">{e.source}</span>
                      <ArrowRight className="w-3.5 h-3.5 shrink-0" />
                      <span className="text-text">{e.target}</span>
                      {e.label && <Badge color="muted" className="ml-1">{e.label}</Badge>}
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div className="flex justify-between items-center pt-2 border-t border-border-soft">
              <Btn variant="danger" onClick={deleteDiagram} loading={deleting}>
                <Trash2 className="w-3.5 h-3.5" /> Verwijderen
              </Btn>
              <Btn variant="secondary" onClick={closeDetail}>Sluiten</Btn>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
