'use client';

import { LayoutShell } from '@/components/layout-shell';
import { useAnonymousReportsAdmin, useReportStats, useReportRegions, AnonymousReport } from '@/hooks/use-anonymous-reports-admin';
import { Eye, FileVideo, FileAudio, ImageIcon, FileText, MapPin, BarChart3, TrendingUp, Filter, ChevronRight, Calendar, AlertCircle } from 'lucide-react';
import { useState } from 'react';
import { Modal } from '@/components/ui/modal';
import { Button } from '@/components/ui/button';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

export default function AnonymousReportsPage() {
  const [selectedRegion, setSelectedRegion] = useState<string>('');
  const [viewMode, setViewMode] = useState<'list' | 'stats'>('list');
  const [selectedReport, setSelectedReport] = useState<AnonymousReport | null>(null);
  const [dateRange, setDateRange] = useState({
    from: new Date(new Date().setDate(1)).toISOString().split('T')[0],
    to: new Date().toISOString().split('T')[0],
  });

  const { data: reports, isLoading, markAsRead } = useAnonymousReportsAdmin(selectedRegion || undefined);
  const { data: stats, isLoading: statsLoading } = useReportStats(dateRange.from, dateRange.to);
  const { data: regions } = useReportRegions();

  if (isLoading && viewMode === 'list') {
    return (
      <LayoutShell role="SUPER_ADMIN">
        <div className="flex h-96 items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-brand border-t-transparent"></div>
        </div>
      </LayoutShell>
    );
  }

  const getMediaUrl = (path: string | null) => {
    if (!path) return null;
    return `${API_BASE_URL.replace('/api/v1', '')}/${path}`;
  };

  return (
    <LayoutShell role="SUPER_ADMIN">
      <div className="space-y-6">
        {/* Header with View Toggle */}
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-slate-900">See Something Reports</h1>
            <p className="mt-2 text-slate-500">
              Review anonymous reports with location-based insights.
            </p>
          </div>
          <div className="flex items-center gap-2 bg-slate-100 rounded-lg p-1">
            <button
              onClick={() => setViewMode('list')}
              className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition ${viewMode === 'list' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-600 hover:text-slate-900'}`}
            >
              <FileText className="h-4 w-4" />
              Reports
            </button>
            <button
              onClick={() => setViewMode('stats')}
              className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition ${viewMode === 'stats' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-600 hover:text-slate-900'}`}
            >
              <BarChart3 className="h-4 w-4" />
              Analytics
            </button>
          </div>
        </div>

        {/* Stats View */}
        {viewMode === 'stats' && (
          <div className="space-y-6">
            <div className="flex flex-wrap items-center gap-4 p-4 bg-white rounded-lg border shadow-sm">
              <Calendar className="h-5 w-5 text-slate-400" />
              <input type="date" value={dateRange.from} onChange={(e) => setDateRange(prev => ({ ...prev, from: e.target.value }))} className="rounded-md border border-slate-200 px-3 py-2 text-sm" title="Start date" aria-label="Filter reports from date" />
              <span className="text-slate-400">to</span>
              <input type="date" value={dateRange.to} onChange={(e) => setDateRange(prev => ({ ...prev, to: e.target.value }))} className="rounded-md border border-slate-200 px-3 py-2 text-sm" title="End date" aria-label="Filter reports to date" />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl p-6 text-white">
                <div className="text-4xl font-bold">{stats?.totals?.total || 0}</div>
                <div className="text-indigo-100 mt-1">Total Reports</div>
              </div>
              <div className="bg-gradient-to-br from-amber-500 to-orange-600 rounded-2xl p-6 text-white">
                <div className="text-4xl font-bold">{stats?.totals?.unread || 0}</div>
                <div className="text-amber-100 mt-1">Unread Reports</div>
              </div>
              <div className="bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl p-6 text-white">
                <div className="text-4xl font-bold">{stats?.totals?.unique_regions || 0}</div>
                <div className="text-emerald-100 mt-1">Regions Reporting</div>
              </div>
            </div>
            <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
              <div className="p-4 border-b bg-slate-50">
                <h3 className="font-semibold text-slate-900 flex items-center gap-2"><MapPin className="h-5 w-5 text-brand" />Reports by Region</h3>
              </div>
              <div className="divide-y">
                {statsLoading ? <div className="p-8 text-center text-slate-500">Loading...</div> : 
                  stats?.regions?.map((region) => (
                    <div key={region.region} className="p-4 hover:bg-slate-50 cursor-pointer transition" onClick={() => { setSelectedRegion(region.region === 'Unknown' ? '' : region.region); setViewMode('list'); }}>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-brand/10 text-brand"><MapPin className="h-5 w-5" /></div>
                          <div>
                            <div className="font-medium text-slate-900">{region.region}</div>
                            <div className="text-sm text-slate-500">{region.unread_reports > 0 && <span className="text-amber-600 font-medium">{region.unread_reports} unread • </span>}Last: {new Date(region.latest_report).toLocaleDateString()}</div>
                          </div>
                        </div>
                        <div className="flex items-center gap-4">
                          <div className="text-right"><div className="text-2xl font-bold text-slate-900">{region.total_reports}</div><div className="text-xs text-slate-500">reports</div></div>
                          <ChevronRight className="h-5 w-5 text-slate-400" />
                        </div>
                      </div>
                    </div>
                  ))
                }
              </div>
            </div>
          </div>
        )}

        {/* List View */}
        {viewMode === 'list' && (
          <>
            <div className="flex items-center gap-2 overflow-x-auto pb-2">
              <Filter className="h-4 w-4 text-slate-400 shrink-0" />
              <button onClick={() => setSelectedRegion('')} className={`shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition ${!selectedRegion ? 'bg-brand text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>All Regions</button>
              {regions?.map(r => (
                <button key={r.region} onClick={() => setSelectedRegion(r.region === 'Unknown' ? '' : r.region)} className={`shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition ${selectedRegion === r.region ? 'bg-brand text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>{r.region} ({r.count})</button>
              ))}
            </div>
            <div className="rounded-lg border bg-white shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-sm text-left">
                  <thead className="text-xs text-slate-500 uppercase bg-slate-50 border-b">
                    <tr>
                      <th className="px-6 py-3">Date</th>
                      <th className="px-6 py-3">Location</th>
                      <th className="px-6 py-3">Type</th>
                      <th className="px-6 py-3">Content Preview</th>
                      <th className="px-6 py-3 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {reports?.map((report) => (
                      <tr key={report.id} className={`border-b hover:bg-slate-50 ${report.is_read ? 'bg-slate-50/50' : 'bg-white'}`}>
                        <td className="px-6 py-4 font-medium text-slate-900 whitespace-nowrap">
                          <div>{new Date(report.created_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</div>
                          <div className="text-xs text-slate-500">{new Date(report.created_at).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })}</div>
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            <MapPin className="h-4 w-4 text-brand shrink-0" />
                            <span className="inline-flex items-center rounded-full bg-brand/10 px-2.5 py-0.5 text-xs font-medium text-brand">{report.region || 'Unknown'}</span>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          {report.media_type === 'image' && <span className="inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-semibold text-slate-500"><ImageIcon className="w-3 h-3"/> Image</span>}
                          {report.media_type === 'video' && <span className="inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-semibold text-slate-500"><FileVideo className="w-3 h-3"/> Video</span>}
                          {report.media_type === 'audio' && <span className="inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-semibold text-slate-500"><FileAudio className="w-3 h-3"/> Audio</span>}
                          {!report.media_type && <span className="inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-semibold text-slate-500"><FileText className="w-3 h-3"/> Text</span>}
                        </td>
                        <td className="px-6 py-4 max-w-xs truncate text-slate-600">{report.description || <span className="text-slate-400 italic">No description</span>}</td>
                        <td className="px-6 py-4 text-right">
                          <div className="flex items-center justify-end gap-2">
                            {!report.is_read && <span className="inline-flex items-center rounded-full bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700 ring-1 ring-inset ring-blue-700/10">New</span>}
                            <Button variant="ghost" size="sm" onClick={() => { setSelectedReport(report); if (!report.is_read) markAsRead.mutate(report.id); }}><Eye className="mr-2 h-4 w-4" />View</Button>
                          </div>
                        </td>
                      </tr>
                    ))}
                    {reports?.length === 0 && <tr><td colSpan={5} className="h-32 text-center text-slate-500"><div className="flex flex-col items-center gap-2"><AlertCircle className="h-8 w-8 text-slate-300" /><span>No reports found.</span></div></td></tr>}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        )}
      </div>

      <Modal isOpen={!!selectedReport} onClose={() => setSelectedReport(null)} title="Report Details" size="lg">
        {selectedReport && (
          <div className="space-y-6">
            <div className="flex items-center gap-4 text-sm text-slate-500 border-b pb-4">
              <div className="flex flex-col"><span className="text-xs uppercase tracking-wider text-slate-400">Timestamp</span><span className="font-medium text-slate-900">{new Date(selectedReport.created_at).toLocaleString()}</span></div>
              <div className="h-8 w-px bg-slate-200" />
              <div className="flex flex-col"><span className="text-xs uppercase tracking-wider text-slate-400">Type</span><span className="font-medium text-slate-900 capitalize">{selectedReport.media_type || 'Text Only'}</span></div>
            </div>
            <div className="bg-brand/5 p-4 rounded-lg border border-brand/20">
              <h4 className="text-xs uppercase tracking-wider text-slate-500 mb-2 flex items-center gap-2"><MapPin className="h-4 w-4 text-brand" />Location</h4>
              <div className="space-y-2">
                <span className="inline-flex items-center rounded-full bg-brand px-3 py-1 text-sm font-medium text-white">{selectedReport.region || 'Unknown'} Region</span>
                {selectedReport.address && <p className="text-sm text-slate-600">{selectedReport.address}</p>}
                {selectedReport.latitude && selectedReport.longitude && (
                  <a href={`https://www.google.com/maps?q=${selectedReport.latitude},${selectedReport.longitude}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-sm text-brand hover:underline">View on Google Maps →</a>
                )}
              </div>
            </div>
            {selectedReport.description && <div className="bg-slate-50 p-4 rounded-lg border border-slate-200"><h4 className="text-xs uppercase tracking-wider text-slate-500 mb-2">Description</h4><p className="whitespace-pre-wrap text-slate-800 leading-relaxed">{selectedReport.description}</p></div>}
            {selectedReport.media_path && (
              <div>
                <h4 className="text-xs uppercase tracking-wider text-slate-500 mb-2">Evidence Attachment</h4>
                <div className="rounded-lg overflow-hidden border bg-slate-100 flex items-center justify-center min-h-[200px] max-h-[600px]">
                  {selectedReport.media_type === 'image' && <img src={getMediaUrl(selectedReport.media_path) || ''} alt="Evidence" className="w-full h-auto object-contain" />}
                  {selectedReport.media_type === 'video' && <video controls className="w-full h-full max-h-[600px]" src={getMediaUrl(selectedReport.media_path) || ''} />}
                  {selectedReport.media_type === 'audio' && <audio controls className="w-full p-4" src={getMediaUrl(selectedReport.media_path) || ''} />}
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </LayoutShell>
  );
}
