'use client';

import { LayoutShell } from '@/components/layout-shell';
import api from '@/lib/api-client';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { AlertTriangle, FileWarning, MapPin, RefreshCw, Truck } from 'lucide-react';
import { useState } from 'react';
import { Modal } from '@/components/ui/modal';
import { ReportEvidence } from '@/components/report-evidence';

type Feed = 'deliveries' | 'anonymous-reports' | 'issue-reports';

const FEEDS: { value: Feed; label: string; icon: typeof Truck }[] = [
  { value: 'deliveries', label: 'Deliveries', icon: Truck },
  { value: 'anonymous-reports', label: 'See Something', icon: MapPin },
  { value: 'issue-reports', label: 'App Issues', icon: FileWarning },
];

export default function FieldReportsPage() {
  const [feed, setFeed] = useState<Feed>('deliveries');
  const [periodId, setPeriodId] = useState('');
  const [selected, setSelected] = useState<any | null>(null);
  const periods = useQuery({
    queryKey: ['plan-periods'],
    queryFn: async () => (await api.get('/plan-periods', { params: { per_page: 100 } })).data,
  });
  const summary = useQuery({
    queryKey: ['field-reports-summary'],
    queryFn: async () => (await api.get('/admin/field-reports/summary')).data,
    refetchInterval: 30000,
  });
  const reports = useInfiniteQuery({
    queryKey: ['field-reports', feed, feed === 'deliveries' ? periodId : ''],
    initialPageParam: '' as string,
    queryFn: async ({ pageParam }) => (await api.get('/admin/field-reports/' + feed, {
      params: {
        limit: 50, order: 'desc', cursor: pageParam || undefined,
        plan_period_id: feed === 'deliveries' && periodId ? periodId : undefined,
      },
    })).data,
    getNextPageParam: (lastPage: any) => lastPage.has_more ? lastPage.next_cursor : undefined,
    refetchInterval: 30000,
  });
  const items = reports.data?.pages.flatMap(page => page.items || []) || [];

  const refresh = async () => {
    await Promise.all([summary.refetch(), reports.refetch()]);
  };

  return (
    <LayoutShell role="SUPER_ADMIN">
      <div className="space-y-5">
        <div className="flex items-end justify-between border-b border-slate-200 pb-5">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">Field Reports</h1>
            <p className="mt-1 text-sm text-slate-500">All records submitted from the live field application.</p>
          </div>
          <button
            onClick={refresh}
            disabled={summary.isFetching || reports.isFetching}
            title="Refresh field reports"
            className="rounded-md border border-slate-300 bg-white p-2.5 text-slate-600 hover:bg-slate-50 disabled:opacity-50"
          >
            <RefreshCw className={`h-4 w-4 ${(summary.isFetching || reports.isFetching) ? 'animate-spin' : ''}`} />
          </button>
        </div>

        {feed === 'deliveries' && (
          <select aria-label="Filter by plan period" value={periodId} onChange={event => setPeriodId(event.target.value)} className="max-w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm text-slate-700">
            <option value="">All plan periods</option>
            {periods.data?.data?.map((period: any) => <option key={period.id} value={period.id}>{period.label}</option>)}
          </select>
        )}

        <div className="grid grid-cols-1 divide-y divide-slate-200 rounded-lg border border-slate-200 bg-white sm:grid-cols-3 sm:divide-x sm:divide-y-0">
          {FEEDS.map(item => {
            const Icon = item.icon;
            const value = summary.data?.feeds?.[item.value]?.total ?? 0;
            return (
              <button key={item.value} onClick={() => setFeed(item.value)} className="flex items-center gap-3 px-5 py-4 text-left hover:bg-slate-50">
                <Icon className="h-5 w-5 text-slate-400" />
                <span>
                  <span className="block text-xs font-semibold uppercase text-slate-500">{item.label}</span>
                  <span className="block text-xl font-bold text-slate-900">{Number(value).toLocaleString()}</span>
                </span>
              </button>
            );
          })}
        </div>

        <div className="border-b border-slate-200">
          <nav className="flex gap-6" aria-label="Report feeds">
            {FEEDS.map(item => (
              <button
                key={item.value}
                onClick={() => setFeed(item.value)}
                className={`border-b-2 px-1 pb-3 text-sm font-semibold ${feed === item.value ? 'border-brand text-brand' : 'border-transparent text-slate-500 hover:text-slate-800'}`}
              >
                {item.label}
              </button>
            ))}
          </nav>
        </div>

        <section className="overflow-hidden rounded-lg border border-slate-200 bg-white">
          {reports.isLoading ? (
            <div className="py-16 text-center text-sm text-slate-500">Loading field reports...</div>
          ) : reports.isError ? (
            <div className="flex items-center justify-center gap-2 py-16 text-sm text-rose-600">
              <AlertTriangle className="h-4 w-4" /> Reports could not be loaded.
            </div>
          ) : (
            <div className="overflow-x-auto">
              {feed === 'deliveries' && <DeliveriesTable items={items} onSelect={setSelected} />}
              {feed === 'anonymous-reports' && <AnonymousReportsTable items={items} onSelect={setSelected} />}
              {feed === 'issue-reports' && <IssueReportsTable items={items} onSelect={setSelected} />}
            </div>
          )}
        </section>
        {reports.hasNextPage && (
          <button onClick={() => reports.fetchNextPage()} disabled={reports.isFetchingNextPage} className="rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:opacity-50">
            {reports.isFetchingNextPage ? 'Loading...' : 'Load More'}
          </button>
        )}
      </div>
      <Modal isOpen={selected !== null} onClose={() => setSelected(null)} title="Report Details" size="lg">
        {selected && <ReportDetails item={selected} />}
      </Modal>
    </LayoutShell>
  );
}

function DeliveriesTable({ items, onSelect }: { items: any[]; onSelect: (item: any) => void }) {
  return (
    <table className="min-w-full divide-y divide-slate-200 text-sm">
      <thead className="bg-slate-50 text-left text-xs font-semibold uppercase text-slate-500">
        <tr><th className="px-4 py-3">Date</th><th className="px-4 py-3">School</th><th className="px-4 py-3">Commodity</th><th className="px-4 py-3">Supplier</th><th className="px-4 py-3">Officer</th><th className="px-4 py-3 text-right">Quantity</th><th className="px-4 py-3">Quality</th></tr>
      </thead>
      <tbody className="divide-y divide-slate-100">
        {items.map(item => (
          <tr key={item.id}>
            <td className="whitespace-nowrap px-4 py-3 text-slate-600"><button onClick={() => onSelect(item)} className="font-semibold text-brand hover:underline">{item.delivery_date}</button></td>
            <td className="px-4 py-3"><span className="block font-medium text-slate-900">{item.school?.name}</span><span className="text-xs text-slate-500">{item.school?.region}</span></td>
            <td className="px-4 py-3 text-slate-700">{item.commodity?.name}</td>
            <td className="px-4 py-3 text-slate-700">{item.supplier?.name || 'Not specified'}</td>
            <td className="px-4 py-3 text-slate-700">{item.field_officer?.name}</td>
            <td className="px-4 py-3 text-right font-semibold text-slate-900">{item.actual_quantity} {item.commodity?.unit}</td>
            <td className="px-4 py-3"><Status value={item.quality?.status || item.review_status} warning={item.quality?.has_issues} /></td>
          </tr>
        ))}
        {items.length === 0 && <EmptyRow columns={7} />}
      </tbody>
    </table>
  );
}

function AnonymousReportsTable({ items, onSelect }: { items: any[]; onSelect: (item: any) => void }) {
  return (
    <table className="min-w-full divide-y divide-slate-200 text-sm">
      <thead className="bg-slate-50 text-left text-xs font-semibold uppercase text-slate-500">
        <tr><th className="px-4 py-3">Received</th><th className="px-4 py-3">Region</th><th className="px-4 py-3">Description</th><th className="px-4 py-3">Location</th><th className="px-4 py-3">Evidence</th></tr>
      </thead>
      <tbody className="divide-y divide-slate-100">
        {items.map(item => (
          <tr key={item.id}>
            <td className="whitespace-nowrap px-4 py-3 text-slate-600"><button onClick={() => onSelect(item)} className="font-semibold text-brand hover:underline">{formatDate(item.created_at)}</button></td>
            <td className="px-4 py-3 font-medium text-slate-900">{item.location?.region || 'Unknown'}</td>
            <td className="max-w-md px-4 py-3 text-slate-700"><p className="line-clamp-2">{item.description || 'Media-only report'}</p></td>
            <td className="px-4 py-3 text-slate-600">{item.location ? `${item.location.latitude}, ${item.location.longitude}` : 'Not shared'}</td>
            <td className="px-4 py-3 text-slate-600">{item.media?.type || 'None'}</td>
          </tr>
        ))}
        {items.length === 0 && <EmptyRow columns={5} />}
      </tbody>
    </table>
  );
}

function IssueReportsTable({ items, onSelect }: { items: any[]; onSelect: (item: any) => void }) {
  return (
    <table className="min-w-full divide-y divide-slate-200 text-sm">
      <thead className="bg-slate-50 text-left text-xs font-semibold uppercase text-slate-500">
        <tr><th className="px-4 py-3">Received</th><th className="px-4 py-3">Officer</th><th className="px-4 py-3">Page</th><th className="px-4 py-3">Description</th><th className="px-4 py-3">Status</th></tr>
      </thead>
      <tbody className="divide-y divide-slate-100">
        {items.map(item => (
          <tr key={item.id}>
            <td className="whitespace-nowrap px-4 py-3 text-slate-600"><button onClick={() => onSelect(item)} className="font-semibold text-brand hover:underline">{formatDate(item.created_at)}</button></td>
            <td className="px-4 py-3 font-medium text-slate-900">{item.field_officer?.name}</td>
            <td className="max-w-xs truncate px-4 py-3 text-slate-600" title={item.page_url}>{item.page_url}</td>
            <td className="max-w-md px-4 py-3 text-slate-700"><p className="line-clamp-2">{item.description}</p></td>
            <td className="px-4 py-3"><Status value={item.status} /></td>
          </tr>
        ))}
        {items.length === 0 && <EmptyRow columns={5} />}
      </tbody>
    </table>
  );
}

function Status({ value, warning = false }: { value: string; warning?: boolean }) {
  return <span className={`whitespace-nowrap text-xs font-semibold ${warning ? 'text-amber-700' : 'text-slate-600'}`}>{String(value).replaceAll('_', ' ')}</span>;
}

function EmptyRow({ columns }: { columns: number }) {
  return <tr><td colSpan={columns} className="px-4 py-14 text-center text-slate-500">No records found.</td></tr>;
}

function formatDate(value: string) {
  return value ? new Date(value).toLocaleString() : 'Unknown';
}

function ReportDetails({ item }: { item: any }) {
  const media = [...(item.evidence || []), ...(item.media ? [item.media] : [])];
  return (
    <div className="space-y-5 text-sm text-slate-700">
      <dl className="grid grid-cols-2 gap-x-4 gap-y-3">
        <Detail label="Reference" value={item.id} />
        <Detail label="Received" value={formatDate(item.created_at)} />
        {item.plan_period && <Detail label="Plan period" value={item.plan_period.label} />}
        {item.field_officer && <Detail label="Field officer" value={item.field_officer.name} />}
        {item.school && <Detail label="School" value={item.school.name} />}
        {item.supplier && <Detail label="Supplier" value={item.supplier.name} />}
        {item.commodity && <Detail label="Commodity" value={item.commodity.name} />}
        {item.actual_quantity !== undefined && <Detail label="Delivered" value={item.actual_quantity + ' ' + item.commodity?.unit} />}
        {item.expected_quantity_before !== undefined && <Detail label="Expected before" value={item.expected_quantity_before} />}
        {item.remaining_quantity_after !== undefined && <Detail label="Remaining after" value={item.remaining_quantity_after} />}
        {item.review_status && <Detail label="Review status" value={item.review_status} />}
        {item.flag_reason && <Detail label="Flag reason" value={item.flag_reason} />}
        {item.quality && <Detail label="Quality" value={item.quality.status} />}
        {item.location && <Detail label="Coordinates" value={`${item.location.latitude}, ${item.location.longitude}`} />}
        {item.location && <Detail label="GPS accuracy" value={item.location.accuracy_metres + ' metres'} />}
        {item.location && <Detail label="Region" value={item.location.region || 'Unknown'} />}
        {item.captured_at && <Detail label="Captured" value={formatDate(item.captured_at)} />}
      </dl>
      {item.quality?.issues?.length > 0 && <ul className="list-inside list-disc text-amber-800">{item.quality.issues.map((issue: string) => <li key={issue}>{issue}</li>)}</ul>}
      {item.units?.length > 0 && <div className="divide-y divide-slate-100">{item.units.map((unit: any, index: number) => <p key={index} className="py-2">{unit.quantity} x {unit.unit_name} ({unit.base_unit_total} base units)</p>)}</div>}
      {(item.description || item.notes) && <p className="whitespace-pre-wrap border-t border-slate-200 pt-4 leading-6">{item.description || item.notes}</p>}
      {item.voice_transcript && <div><h3 className="mb-1 font-semibold text-slate-900">Voice transcript</h3><p className="whitespace-pre-wrap">{item.voice_transcript}</p></div>}
      {item.ocr_text && <div><h3 className="mb-1 font-semibold text-slate-900">Receipt text</h3><p className="whitespace-pre-wrap">{item.ocr_text}</p></div>}
      {media.map((entry: any) => <ReportEvidence key={entry.url} entry={entry} />)}
    </div>
  );
}

function Detail({ label, value }: { label: string; value: string }) {
  return <div className="min-w-0"><dt className="text-xs text-slate-500">{label}</dt><dd className="mt-1 break-words font-medium text-slate-900">{value}</dd></div>;
}

