import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { useReports } from '../api/hooks';
import { DataTable, type Column } from '../components/DataTable';
import { StatusBadge, LoadingSpinner } from '../components/ui';
import type { ReportListItem } from '../api/hooks';

export function ReportsPage() {
  const navigate = useNavigate();
  const [reportType, setReportType] = useState('');
  const { data, isLoading } = useReports({
    report_type: reportType || undefined,
    limit: 50,
  });

  const columns: Column<ReportListItem>[] = [
    {
      key: 'report_type',
      header: 'Type',
      render: (r) => (
        <span className="inline-flex items-center rounded px-2 py-0.5 text-xs font-medium bg-surface-700 text-brand-300 capitalize">
          {r.report_type}
        </span>
      ),
    },
    {
      key: 'period_start',
      header: 'Period',
      render: (r) =>
        r.period_start === r.period_end
          ? r.period_start
          : `${r.period_start} → ${r.period_end}`,
    },
    {
      key: 'validation_status',
      header: 'Validation',
      render: (r) => <StatusBadge status={r.validation_status} />,
    },
    {
      key: 'generated_at',
      header: 'Generated',
      render: (r) => (
        <span className="text-xs text-gray-400">
          {new Date(r.generated_at).toLocaleString()}
        </span>
      ),
    },
  ];

  if (isLoading) return <LoadingSpinner />;

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <h1 className="text-xl font-semibold text-gray-100">
          Trading Reports
        </h1>
        <select
          value={reportType}
          onChange={(e) => setReportType(e.target.value)}
          className="rounded border border-surface-600 bg-surface-800 px-3 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
          aria-label="Filter by report type"
        >
          <option value="">All Types</option>
          <option value="daily">Daily</option>
          <option value="weekly">Weekly</option>
        </select>
      </div>
      <DataTable<ReportListItem>
        data={data ?? []}
        columns={columns}
        keyField="id"
        onRowClick={(row) =>
          navigate({ to: '/reports/$id', params: { id: row.id } })
        }
      />
    </div>
  );
}
