'use client';

import { useEffect, useState, useCallback } from 'react';
import { toast } from 'sonner';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
  DialogClose,
} from '@/components/ui/dialog';
import {
  FileText,
  AlertCircle,
  AlertTriangle,
  Info,
  Search,
  Trash2,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  Filter,
  X,
  Copy,
  CheckCircle,
} from 'lucide-react';

interface LogEntry {
  id: string;
  level: string;
  source: string;
  action: string;
  message: string;
  metadata: string | null;
  ip: string | null;
  path: string | null;
  orderId: string | null;
  createdAt: string;
}

interface LogStats {
  errorCount: number;
  warnCount: number;
  infoCount: number;
  total: number;
}

const LEVEL_CONFIG: Record<string, { icon: React.ElementType; color: string; bg: string; badgeClass: string }> = {
  error: {
    icon: AlertCircle,
    color: 'text-red-600',
    bg: 'bg-red-50',
    badgeClass: 'bg-red-100 text-red-800 hover:bg-red-100',
  },
  warn: {
    icon: AlertTriangle,
    color: 'text-amber-600',
    bg: 'bg-amber-50',
    badgeClass: 'bg-amber-100 text-amber-800 hover:bg-amber-100',
  },
  info: {
    icon: Info,
    color: 'text-blue-600',
    bg: 'bg-blue-50',
    badgeClass: 'bg-blue-100 text-blue-800 hover:bg-blue-100',
  },
  debug: {
    icon: FileText,
    color: 'text-gray-600',
    bg: 'bg-gray-50',
    badgeClass: 'bg-gray-100 text-gray-800 hover:bg-gray-100',
  },
};

const SOURCE_COLORS: Record<string, string> = {
  payin: 'bg-emerald-100 text-emerald-800',
  callback: 'bg-violet-100 text-violet-800',
  telegram: 'bg-sky-100 text-sky-800',
  admin: 'bg-gray-100 text-gray-800',
  auth: 'bg-rose-100 text-rose-800',
  screenshot: 'bg-orange-100 text-orange-800',
  system: 'bg-slate-100 text-slate-800',
};

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('en-IN', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

export default function AdminLogsPage() {
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [stats, setStats] = useState<LogStats>({ errorCount: 0, warnCount: 0, infoCount: 0, total: 0 });
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [search, setSearch] = useState('');
  const [level, setLevel] = useState('');
  const [source, setSource] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [selectedLog, setSelectedLog] = useState<LogEntry | null>(null);
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [copied, setCopied] = useState(false);

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        limit: '50',
      });
      if (level) params.set('level', level);
      if (source) params.set('source', source);
      if (search) params.set('search', search);
      if (startDate) params.set('startDate', startDate);
      if (endDate) params.set('endDate', endDate);

      const res = await fetch(`/api/admin/logs?${params}`);
      if (!res.ok) throw new Error('Failed to load logs');
      const data = await res.json();

      setLogs(data.logs);
      setStats(data.stats);
      setTotalPages(data.pagination.totalPages);
    } catch {
      toast.error('Failed to load logs');
    } finally {
      setLoading(false);
    }
  }, [page, level, source, search, startDate, endDate]);

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

  const handleClearFilters = () => {
    setSearch('');
    setLevel('');
    setSource('');
    setStartDate('');
    setEndDate('');
    setPage(1);
  };

  const handlePurgeLogs = async (purgeLevel: string) => {
    try {
      const params = new URLSearchParams();
      if (purgeLevel !== 'all') {
        params.set('level', purgeLevel);
      }
      params.set('beforeDate', new Date().toISOString());

      const res = await fetch(`/api/admin/logs?${params}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to purge logs');
      const data = await res.json();
      toast.success(`Purged ${data.deletedCount} log entries`);
      fetchLogs();
    } catch {
      toast.error('Failed to purge logs');
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const hasFilters = level || source || search || startDate || endDate;

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <FileText className="h-6 w-6 text-emerald-600" />
            System Logs
          </h1>
          <p className="text-sm text-gray-500 mt-1">
            Telemetry, error tracking, and notification logs
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => setFiltersOpen(!filtersOpen)} className={hasFilters ? 'border-emerald-300 text-emerald-700' : ''}>
            <Filter className="mr-2 h-4 w-4" />
            Filters
            {hasFilters && (
              <span className="ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-emerald-100 text-xs text-emerald-700">
                {[level, source, search, startDate, endDate].filter(Boolean).length}
              </span>
            )}
          </Button>
          <Button variant="outline" size="sm" onClick={fetchLogs} disabled={loading}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
          <Dialog>
            <DialogTrigger asChild>
              <Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50">
                <Trash2 className="mr-2 h-4 w-4" />
                Purge
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Purge Logs</DialogTitle>
                <DialogDescription>
                  Delete old log entries. This action cannot be undone.
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-3 py-2">
                <Button
                  variant="outline"
                  className="w-full justify-start text-red-600 hover:bg-red-50"
                  onClick={() => handlePurgeLogs('error')}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Purge Error Logs
                </Button>
                <Button
                  variant="outline"
                  className="w-full justify-start text-amber-600 hover:bg-amber-50"
                  onClick={() => handlePurgeLogs('warn')}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Purge Warning Logs
                </Button>
                <Button
                  variant="outline"
                  className="w-full justify-start text-gray-600 hover:bg-gray-50"
                  onClick={() => handlePurgeLogs('all')}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Purge All Logs
                </Button>
              </div>
              <DialogFooter>
                <DialogClose asChild>
                  <Button variant="ghost">Cancel</Button>
                </DialogClose>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="shadow-sm">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-50">
                <Info className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Info</p>
                <p className="text-xl font-bold text-gray-900">{stats.infoCount}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="shadow-sm">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-amber-50">
                <AlertTriangle className="h-5 w-5 text-amber-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Warnings</p>
                <p className="text-xl font-bold text-gray-900">{stats.warnCount}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="shadow-sm">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-red-50">
                <AlertCircle className="h-5 w-5 text-red-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Errors</p>
                <p className="text-xl font-bold text-gray-900">{stats.errorCount}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card className="shadow-sm">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gray-100">
                <FileText className="h-5 w-5 text-gray-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Total</p>
                <p className="text-xl font-bold text-gray-900">{stats.total}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters Panel */}
      {filtersOpen && (
        <Card className="shadow-sm">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">Filters</CardTitle>
              <div className="flex items-center gap-2">
                {hasFilters && (
                  <Button variant="ghost" size="sm" onClick={handleClearFilters}>
                    <X className="mr-1 h-3 w-3" />
                    Clear All
                  </Button>
                )}
                <Button variant="ghost" size="sm" onClick={() => setFiltersOpen(false)}>
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium text-gray-500">Search</Label>
                <div className="relative">
                  <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
                  <Input
                    placeholder="Search messages, actions..."
                    value={search}
                    onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                    className="pl-9 h-9"
                  />
                </div>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium text-gray-500">Level</Label>
                <Select value={level} onValueChange={(v) => { setLevel(v === 'all' ? '' : v); setPage(1); }}>
                  <SelectTrigger className="h-9">
                    <SelectValue placeholder="All Levels" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Levels</SelectItem>
                    <SelectItem value="error">Error</SelectItem>
                    <SelectItem value="warn">Warning</SelectItem>
                    <SelectItem value="info">Info</SelectItem>
                    <SelectItem value="debug">Debug</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium text-gray-500">Source</Label>
                <Select value={source} onValueChange={(v) => { setSource(v === 'all' ? '' : v); setPage(1); }}>
                  <SelectTrigger className="h-9">
                    <SelectValue placeholder="All Sources" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Sources</SelectItem>
                    <SelectItem value="payin">Payin</SelectItem>
                    <SelectItem value="callback">Callback</SelectItem>
                    <SelectItem value="telegram">Telegram</SelectItem>
                    <SelectItem value="admin">Admin</SelectItem>
                    <SelectItem value="auth">Auth</SelectItem>
                    <SelectItem value="screenshot">Screenshot</SelectItem>
                    <SelectItem value="system">System</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium text-gray-500">From</Label>
                  <Input
                    type="date"
                    value={startDate}
                    onChange={(e) => { setStartDate(e.target.value); setPage(1); }}
                    className="h-9"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium text-gray-500">To</Label>
                  <Input
                    type="date"
                    value={endDate}
                    onChange={(e) => { setEndDate(e.target.value); setPage(1); }}
                    className="h-9"
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Logs Table */}
      <Card className="shadow-sm">
        <CardContent className="p-0">
          {loading ? (
            <div className="space-y-3 p-6">
              {Array.from({ length: 8 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : logs.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16">
              <FileText className="h-12 w-12 text-gray-300 mb-4" />
              <p className="text-gray-500 font-medium">No logs found</p>
              <p className="text-sm text-gray-400 mt-1">
                {hasFilters ? 'Try adjusting your filters' : 'Logs will appear as events happen'}
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto -mx-1">
              <Table className="min-w-[700px]">
                <TableHeader>
                  <TableRow className="bg-gray-50/50">
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase w-20">Level</TableHead>
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase w-24">Source</TableHead>
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase w-36">Action</TableHead>
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase">Message</TableHead>
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase w-36 hidden md:table-cell">IP</TableHead>
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase w-44 hidden sm:table-cell">Time</TableHead>
                    <TableHead className="text-xs font-semibold text-gray-500 uppercase w-16"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {logs.map((log) => {
                    const config = LEVEL_CONFIG[log.level] || LEVEL_CONFIG.info;
                    const Icon = config.icon;
                    const sourceColor = SOURCE_COLORS[log.source] || 'bg-gray-100 text-gray-800';

                    return (
                      <TableRow
                        key={log.id}
                        className={`cursor-pointer transition-colors hover:bg-gray-50 ${log.level === 'error' ? 'bg-red-50/30' : ''}`}
                        onClick={() => setSelectedLog(log)}
                      >
                        <TableCell>
                          <Badge variant="secondary" className={`text-xs font-medium ${config.badgeClass}`}>
                            <Icon className="mr-1 h-3 w-3" />
                            {log.level}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="secondary" className={`text-xs font-medium ${sourceColor}`}>
                            {log.source}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm font-mono text-gray-700 truncate block max-w-[140px]">
                            {log.action}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm text-gray-600 truncate block max-w-[300px]">
                            {log.message}
                          </span>
                          {log.orderId && (
                            <span className="text-xs text-emerald-600 font-mono">
                              Order: {log.orderId}
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          <span className="text-xs text-gray-400 font-mono">
                            {log.ip || '-'}
                          </span>
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">
                          <span className="text-xs text-gray-500">
                            {formatDate(log.createdAt)}
                          </span>
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7"
                            onClick={(e) => {
                              e.stopPropagation();
                              const fullLog = JSON.stringify(log, null, 2);
                              copyToClipboard(fullLog);
                            }}
                          >
                            {copied ? (
                              <CheckCircle className="h-3.5 w-3.5 text-green-500" />
                            ) : (
                              <Copy className="h-3.5 w-3.5 text-gray-400" />
                            )}
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">
            Page {page} of {totalPages} ({stats.total} total entries)
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(1)}
              disabled={page === 1}
            >
              First
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm font-medium px-3">{page} / {totalPages}</span>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(totalPages)}
              disabled={page === totalPages}
            >
              Last
            </Button>
          </div>
        </div>
      )}

      {/* Log Detail Dialog */}
      <Dialog open={!!selectedLog} onOpenChange={() => setSelectedLog(null)}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              Log Detail
              {selectedLog && (
                <Badge variant="secondary" className={`${LEVEL_CONFIG[selectedLog.level]?.badgeClass || ''}`}>
                  {selectedLog.level}
                </Badge>
              )}
            </DialogTitle>
            <DialogDescription>
              {selectedLog?.action}
            </DialogDescription>
          </DialogHeader>
          {selectedLog && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-medium text-gray-500">Source</Label>
                  <p className="mt-1">
                    <Badge variant="secondary" className={SOURCE_COLORS[selectedLog.source] || ''}>
                      {selectedLog.source}
                    </Badge>
                  </p>
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500">Time</Label>
                  <p className="mt-1 text-sm text-gray-700">{formatDate(selectedLog.createdAt)}</p>
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500">IP Address</Label>
                  <p className="mt-1 text-sm font-mono text-gray-700">{selectedLog.ip || '-'}</p>
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500">Path</Label>
                  <p className="mt-1 text-sm font-mono text-gray-700">{selectedLog.path || '-'}</p>
                </div>
                {selectedLog.orderId && (
                  <div className="col-span-2">
                    <Label className="text-xs font-medium text-gray-500">Order ID</Label>
                    <p className="mt-1 text-sm font-mono text-emerald-600">{selectedLog.orderId}</p>
                  </div>
                )}
              </div>
              <div>
                <Label className="text-xs font-medium text-gray-500">Message</Label>
                <p className="mt-1 text-sm text-gray-700 bg-gray-50 rounded-lg p-3">{selectedLog.message}</p>
              </div>
              {selectedLog.metadata && (
                <div>
                  <Label className="text-xs font-medium text-gray-500">Metadata</Label>
                  <pre className="mt-1 text-xs text-gray-700 bg-gray-900 text-green-400 rounded-lg p-3 overflow-x-auto max-h-60">
                    {(() => {
                      try {
                        return JSON.stringify(JSON.parse(selectedLog.metadata), null, 2);
                      } catch {
                        return selectedLog.metadata;
                      }
                    })()}
                  </pre>
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button
              variant="outline"
              size="sm"
              onClick={() => selectedLog && copyToClipboard(JSON.stringify(selectedLog, null, 2))}
            >
              {copied ? <CheckCircle className="mr-2 h-4 w-4 text-green-500" /> : <Copy className="mr-2 h-4 w-4" />}
              {copied ? 'Copied!' : 'Copy JSON'}
            </Button>
            <DialogClose asChild>
              <Button size="sm">Close</Button>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
