import { useState, useEffect, useCallback } from 'react';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { Modal } from '../../components/ui/Modal';
import { Button } from '../../components/ui/Button';
import { GradientButton } from '../../components/ui/GradientButton';
import { api } from '../../api/client';
import type { Report } from '../../types';

const TABS = ['ALL', 'OPEN', 'REVIEWING', 'RESOLVED', 'DISMISSED'];

export function AdminReportsPage() {
  const [reports, setReports] = useState<Report[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [tab, setTab] = useState('ALL');
  const [selected, setSelected] = useState<Report | null>(null);
  const [resolution, setResolution] = useState('');

  const fetchReports = useCallback(async () => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    if (tab !== 'ALL') params.set('status', tab);
    const res = await api.get<{ data: Report[]; total: number }>(`/admin/reports?${params}`);
    setReports(res.data);
    setTotal(res.total);
  }, [page, tab]);

  useEffect(() => { fetchReports(); }, [fetchReports]);

  const handleResolve = async (status: 'RESOLVED' | 'DISMISSED') => {
    if (!selected) return;
    await api.patch(`/admin/reports/${selected.id}`, { status, resolution: resolution || undefined });
    setSelected(null);
    setResolution('');
    fetchReports();
  };

  const statusBadge = (status: string) => {
    const v = status === 'OPEN' ? 'warning' : status === 'REVIEWING' ? 'info' : status === 'RESOLVED' ? 'success' : 'default';
    return <Badge variant={v} size="sm">{status}</Badge>;
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-4">Reports</h1>
      <div className="flex gap-2 mb-4 flex-wrap">
        {TABS.map((t) => (
          <button
            key={t}
            onClick={() => { setTab(t); setPage(1); }}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors cursor-pointer ${
              tab === t ? 'bg-primary-100 text-primary-700' : 'text-gray-500 hover:bg-gray-100'
            }`}
          >
            {t}
          </button>
        ))}
      </div>
      <DataTable
        columns={[
          { key: 'targetType', header: 'Type', render: (r: Report) => <Badge variant="default" size="sm">{r.targetType}</Badge> },
          { key: 'reason', header: 'Reason', render: (r: Report) => r.reason.replace('_', ' ') },
          { key: 'reporter', header: 'Reporter', render: (r: Report) => r.reporter?.fullName || 'Unknown' },
          { key: 'status', header: 'Status', render: (r: Report) => statusBadge(r.status) },
          { key: 'createdAt', header: 'Date', render: (r: Report) => new Date(r.createdAt).toLocaleDateString() },
        ]}
        data={reports}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        actions={(r: Report) =>
          r.status === 'OPEN' || r.status === 'REVIEWING' ? (
            <button onClick={() => setSelected(r)} className="text-sm text-primary-600 hover:text-primary-700 font-medium cursor-pointer">
              Review
            </button>
          ) : null
        }
      />

      <Modal isOpen={!!selected} onClose={() => setSelected(null)} title="Review Report" size="sm">
        {selected && (
          <>
            <div className="space-y-2 mb-4 text-sm">
              <p><span className="font-medium">Type:</span> {selected.targetType}</p>
              <p><span className="font-medium">Reason:</span> {selected.reason}</p>
              {selected.description && <p><span className="font-medium">Details:</span> {selected.description}</p>}
            </div>
            <textarea
              value={resolution}
              onChange={(e) => setResolution(e.target.value)}
              rows={2}
              placeholder="Resolution notes (optional)..."
              className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm placeholder:text-gray-400 focus:border-primary-400 focus:outline-none resize-none mb-4"
            />
            <div className="flex gap-3">
              <Button variant="secondary" className="flex-1" onClick={() => handleResolve('DISMISSED')}>Dismiss</Button>
              <GradientButton className="flex-1" onClick={() => handleResolve('RESOLVED')}>Resolve</GradientButton>
            </div>
          </>
        )}
      </Modal>
    </div>
  );
}
