import { useEffect, useState, useMemo, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import Layout from '../components/Layout';
import RecordModal from '../components/RecordModal';
import CreateModal, { hasCreateForm } from '../components/CreateModal';
import { fetchAll, apiDelete } from '../lib/api';
import { TABLES, STATUS_COLORS } from '../lib/tables';

function truncate(str, n = 60) {
  if (str == null) return '—';
  const s = String(str);
  return s.length > n ? s.slice(0, n) + '…' : s;
}

function CellValue({ col, value, linkedFields, navigate }) {
  if (value == null || value === '') return <span className="text-slate-300">—</span>;

  // Array of IDs (e.g. picture_ids, word_ids)
  if (Array.isArray(value)) {
    if (value.length === 0) return <span className="text-slate-300">[]</span>;
    const targetTable = linkedFields[col];
    return (
      <div className="flex flex-wrap gap-1">
        {value.slice(0, 3).map(id => (
          <button
            key={id}
            onClick={e => { e.stopPropagation(); targetTable && navigate(`/db/${targetTable}?id=${id}`); }}
            className="text-xs bg-indigo-50 text-indigo-600 rounded px-1.5 py-0.5 hover:bg-indigo-100 font-mono"
            title={String(id)}
          >
            {String(id).slice(0, 8)}
          </button>
        ))}
        {value.length > 3 && (
          <span className="text-xs text-slate-400">+{value.length - 3}</span>
        )}
      </div>
    );
  }

  // Single UUID FK (e.g. question_id)
  if (typeof value === 'string' && linkedFields[col]) {
    const targetTable = linkedFields[col];
    return (
      <button
        onClick={e => { e.stopPropagation(); navigate(`/db/${targetTable}?id=${value}`); }}
        className="text-xs bg-indigo-50 text-indigo-600 rounded px-1.5 py-0.5 hover:bg-indigo-100 font-mono"
        title={value}
      >
        {value.slice(0, 8)}…
      </button>
    );
  }

  // Status badge
  if (col === 'status') {
    const cls = STATUS_COLORS[value] || 'bg-slate-100 text-slate-600';
    return <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${cls}`}>{value}</span>;
  }

  // Timestamp
  if (col.endsWith('_at') || col.endsWith('_timestamp')) {
    return <span className="text-xs text-slate-500">{new Date(value).toLocaleDateString('de-DE')}</span>;
  }

  // Picture link — show as thumbnail + link
  if (col === 'picture_link') {
    return (
      <a href={value} target="_blank" rel="noreferrer" className="text-xs text-indigo-600 underline">
        Bild öffnen
      </a>
    );
  }

  return <span className="text-sm text-slate-700">{truncate(value)}</span>;
}

export default function TableView() {
  const { tableKey } = useParams();
  const navigate = useNavigate();
  const meta = TABLES[tableKey];

  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [textFilter, setTextFilter] = useState('');
  const [highlightId, setHighlightId] = useState(null);
  const [modalRecord, setModalRecord] = useState(null);
  const [showCreate, setShowCreate] = useState(false);
  const [confirmDeleteId, setConfirmDeleteId] = useState(null);
  const [deleting, setDeleting] = useState(false);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const id = params.get('id');
    if (id) setHighlightId(id);
  }, []);

  useEffect(() => {
    if (!meta) return;
    setLoading(true);
    fetchAll(meta.endpoint)
      .then(data => setRows(Array.isArray(data) ? data : []))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, [meta]);

  const statuses = useMemo(() => {
    const set = new Set(rows.map(r => r.status).filter(Boolean));
    return [...set].sort();
  }, [rows]);

  const filtered = useMemo(() => {
    return rows.filter(row => {
      if (statusFilter && row.status !== statusFilter) return false;
      if (textFilter) {
        const q = textFilter.toLowerCase();
        return Object.values(row).some(v =>
          v != null && String(v).toLowerCase().includes(q)
        );
      }
      return true;
    });
  }, [rows, statusFilter, textFilter]);

  function handleRecordSaved(updated) {
    setRows(prev => prev.map(r => (r.id === updated.id ? { ...r, ...updated } : r)));
  }

  function handleRecordCreated(newRecord) {
    setRows(prev => [newRecord, ...prev]);
  }

  const handleDelete = useCallback(async (id, e) => {
    e.stopPropagation();
    setDeleting(true);
    try {
      await apiDelete(meta.endpoint, id);
      setRows(prev => prev.filter(r => r.id !== id));
      setConfirmDeleteId(null);
      if (modalRecord?.id === id) setModalRecord(null);
    } catch (err) {
      alert('Fehler beim Löschen: ' + err.message);
    } finally {
      setDeleting(false);
    }
  }, [meta, modalRecord]);

  if (!meta) return <Layout back="/db"><p className="text-red-500">Unbekannte Tabelle: {tableKey}</p></Layout>;

  return (
    <Layout back="/db">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xl font-semibold text-slate-700">
          {meta.icon} {meta.label}
          <span className="ml-2 text-base font-normal text-slate-400">
            ({filtered.length}{rows.length === 500 ? '+' : ''} von {rows.length}{rows.length === 500 ? '+' : ''})
          </span>
        </h2>
        {hasCreateForm(tableKey) && (
          <button
            onClick={() => setShowCreate(true)}
            className="flex items-center gap-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-medium px-3 py-1.5 rounded-lg transition-colors"
          >
            <span className="text-lg leading-none">+</span> Neu
          </button>
        )}
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 mb-4">
        <input
          type="text"
          placeholder="Suche (contains)…"
          value={textFilter}
          onChange={e => setTextFilter(e.target.value)}
          className="border border-slate-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 bg-white w-56"
        />
        {meta.statusField && statuses.length > 0 && (
          <select
            value={statusFilter}
            onChange={e => setStatusFilter(e.target.value)}
            className="border border-slate-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 bg-white"
          >
            <option value="">Alle Status</option>
            {statuses.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        )}
        {(statusFilter || textFilter) && (
          <button
            onClick={() => { setStatusFilter(''); setTextFilter(''); }}
            className="text-sm text-slate-500 hover:text-slate-700 underline"
          >
            Filter zurücksetzen
          </button>
        )}
      </div>

      {error && <div className="text-red-500 text-sm mb-4">{error}</div>}

      {loading ? (
        <div className="space-y-2">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="h-10 bg-white rounded-lg animate-pulse" />
          ))}
        </div>
      ) : (
        <div className="bg-white rounded-2xl shadow-sm overflow-auto border border-slate-200">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-200">
                {meta.columns.map(col => (
                  <th key={col} className="text-left px-4 py-2.5 text-xs font-semibold text-slate-500 uppercase tracking-wide whitespace-nowrap">
                    {col}
                  </th>
                ))}
                <th className="px-3 py-2.5 w-10" />
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={meta.columns.length + 1} className="text-center py-10 text-slate-400">
                    Keine Einträge gefunden
                  </td>
                </tr>
              )}
              {filtered.map((row, i) => (
                <tr
                  key={row.id || i}
                  onClick={() => setModalRecord(row)}
                  className={`group border-b border-slate-100 hover:bg-slate-50 transition-colors cursor-pointer
                    ${highlightId && row.id === highlightId ? 'bg-indigo-50 ring-1 ring-indigo-300' : ''}`}
                >
                  {meta.columns.map(col => (
                    <td key={col} className="px-4 py-2.5 align-top max-w-[280px]">
                      <CellValue
                        col={col}
                        value={row[col]}
                        linkedFields={meta.linkedFields}
                        navigate={navigate}
                      />
                    </td>
                  ))}
                  {/* Delete cell */}
                  <td className="px-3 py-2 text-right align-middle" onClick={e => e.stopPropagation()}>
                    {confirmDeleteId === row.id ? (
                      <span className="flex items-center justify-end gap-1">
                        <button
                          onClick={e => handleDelete(row.id, e)}
                          disabled={deleting}
                          className="text-xs text-white bg-red-500 hover:bg-red-600 rounded px-1.5 py-0.5 font-medium disabled:opacity-50"
                        >
                          {deleting ? '…' : '✓'}
                        </button>
                        <button
                          onClick={e => { e.stopPropagation(); setConfirmDeleteId(null); }}
                          className="text-xs text-slate-500 hover:text-slate-700 bg-slate-100 hover:bg-slate-200 rounded px-1.5 py-0.5"
                        >
                          ✕
                        </button>
                      </span>
                    ) : (
                      <button
                        onClick={e => { e.stopPropagation(); setConfirmDeleteId(row.id); }}
                        className="opacity-0 group-hover:opacity-100 text-slate-300 hover:text-red-400 transition-colors p-1 rounded"
                        title="Löschen"
                      >
                        🗑
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {modalRecord && (
        <RecordModal
          record={modalRecord}
          meta={meta}
          onClose={() => setModalRecord(null)}
          onSaved={handleRecordSaved}
        />
      )}

      {showCreate && (
        <CreateModal
          tableKey={tableKey}
          meta={meta}
          onClose={() => setShowCreate(false)}
          onCreated={handleRecordCreated}
        />
      )}
    </Layout>
  );
}
