'use client'

import { useState, useEffect, useCallback, useRef } from 'react'
import {
  Search,
  Filter,
  RefreshCw,
  ScrollText,
  AlertTriangle,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  Clock,
  Zap,
  Monitor,
  Shield,
  Wifi,
  Settings,
  X,
  FileText,
  Activity,
  User,
  ToggleLeft,
  Loader2,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
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 { api } from '@/lib/api'

// ---- Types ----
interface LogEntry {
  id: string
  timestamp: string
  userId: string
  userName: string
  action: string
  module: string
  details: string
  ipAddress: string
}

interface LogSummary {
  totalLogs: number
  todayLogs: number
  mostActiveModule: string
  recentActions: string[]
}

// ---- Constants ----
const MODULE_OPTIONS = [
  { value: 'all', label: 'All Modules' },
  { value: 'Login', label: 'Login' },
  { value: 'Billing', label: 'Billing' },
  { value: 'Support', label: 'Support' },
  { value: 'Network', label: 'Network' },
  { value: 'System', label: 'System' },
]

const moduleBadgeColor: Record<string, string> = {
  Login: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  Billing: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  Support: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  Network: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-400',
  System: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
}

const moduleIcons: Record<string, React.ElementType> = {
  Login: Shield,
  Billing: Activity,
  Support: Monitor,
  Network: Wifi,
  System: Settings,
}

// ---- Skeleton Components ----
function SummaryCardSkeleton() {
  return (
    <Card className="p-4">
      <div className="flex items-center gap-4">
        <Skeleton className="size-10 rounded-lg" />
        <div className="flex-1 space-y-2">
          <Skeleton className="h-4 w-24" />
          <Skeleton className="h-7 w-16" />
        </div>
      </div>
    </Card>
  )
}

function TableSkeleton() {
  return (
    <div className="space-y-3">
      <Skeleton className="h-10 w-full" />
      {Array.from({ length: 8 }).map((_, i) => (
        <Skeleton key={i} className="h-12 w-full" />
      ))}
    </div>
  )
}

// ---- Format Helpers ----
function formatTimestamp(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

// ---- Pagination ----
function Pagination({
  page,
  totalPages,
  onPageChange,
}: {
  page: number
  totalPages: number
  onPageChange: (page: number) => void
}) {
  if (totalPages <= 1) return null

  return (
    <div className="flex items-center justify-between gap-4 pt-4">
      <p className="text-sm text-muted-foreground">
        Page {page} of {totalPages}
      </p>
      <div className="flex items-center gap-1">
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(1)}
          disabled={page <= 1}
        >
          <ChevronsLeft className="size-4" />
        </Button>
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(page - 1)}
          disabled={page <= 1}
        >
          <ChevronLeft className="size-4" />
        </Button>
        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
          let pageNum: number
          if (totalPages <= 5) {
            pageNum = i + 1
          } else if (page <= 3) {
            pageNum = i + 1
          } else if (page >= totalPages - 2) {
            pageNum = totalPages - 4 + i
          } else {
            pageNum = page - 2 + i
          }
          return (
            <Button
              key={pageNum}
              variant={pageNum === page ? 'default' : 'outline'}
              size="icon"
              className="size-8"
              onClick={() => onPageChange(pageNum)}
            >
              {pageNum}
            </Button>
          )
        })}
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(page + 1)}
          disabled={page >= totalPages}
        >
          <ChevronRight className="size-4" />
        </Button>
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(totalPages)}
          disabled={page >= totalPages}
        >
          <ChevronsRight className="size-4" />
        </Button>
      </div>
    </div>
  )
}

// ---- Main Component ----
export default function LogsView() {
  // Data state
  const [logs, setLogs] = useState<LogEntry[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [totalPages, setTotalPages] = useState(0)
  const [total, setTotal] = useState(0)

  // Summary
  const [summary, setSummary] = useState<LogSummary>({
    totalLogs: 0,
    todayLogs: 0,
    mostActiveModule: 'N/A',
    recentActions: [],
  })
  const [summaryLoading, setSummaryLoading] = useState(true)

  // Filters
  const [moduleFilter, setModuleFilter] = useState<string>('all')
  const [actionFilter, setActionFilter] = useState<string>('')
  const [searchInput, setSearchInput] = useState('')
  const [searchQuery, setSearchQuery] = useState('')
  const [userFilter, setUserFilter] = useState<string>('')
  const [startDate, setStartDate] = useState<string>('')
  const [endDate, setEndDate] = useState<string>('')
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(25)

  // Auto-refresh
  const [autoRefresh, setAutoRefresh] = useState(false)
  const autoRefreshRef = useRef<ReturnType<typeof setInterval> | null>(null)

  // Search debounce
  useEffect(() => {
    const timeout = setTimeout(() => {
      setSearchQuery(searchInput)
    }, 400)
    return () => clearTimeout(timeout)
  }, [searchInput])

  // Reset page when filters change
  useEffect(() => {
    setPage(1)
  }, [moduleFilter, actionFilter, searchQuery, userFilter, startDate, endDate, limit])

  // Fetch logs
  const fetchLogs = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params: Record<string, string | number> = {
        page,
        limit,
      }
      if (moduleFilter && moduleFilter !== 'all') params.module = moduleFilter
      if (actionFilter) params.action = actionFilter
      if (searchQuery) params.search = searchQuery
      if (userFilter) params.userId = userFilter
      if (startDate) params.startDate = startDate
      if (endDate) params.endDate = endDate

      const res = await api.get<{ data: LogEntry[] }>('/api/logs', params)

      if (res.success && res.data) {
        const data = res.data.data || res.data
        if (Array.isArray(data)) {
          setLogs(data)
        } else {
          setLogs([])
        }
        if (res.pagination) {
          setTotalPages(res.pagination.totalPages)
          setTotal(res.pagination.total)
        } else {
          setTotalPages(1)
          setTotal(Array.isArray(data) ? data.length : 0)
        }
      } else {
        setError(res.error || 'Failed to load logs')
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Network error'
      setError(message)
    } finally {
      setLoading(false)
    }
  }, [moduleFilter, actionFilter, searchQuery, userFilter, startDate, endDate, page, limit])

  // Auto-refresh effect
  useEffect(() => {
    if (autoRefresh) {
      autoRefreshRef.current = setInterval(() => {
        fetchLogs()
      }, 15000)
    } else {
      if (autoRefreshRef.current) {
        clearInterval(autoRefreshRef.current)
        autoRefreshRef.current = null
      }
    }
    return () => {
      if (autoRefreshRef.current) clearInterval(autoRefreshRef.current)
    }
  }, [autoRefresh, fetchLogs])

  // Fetch summary
  const fetchSummary = useCallback(async () => {
    setSummaryLoading(true)
    try {
      const res = await api.get<{ data: LogEntry[] }>('/api/logs', { limit: 100 })
      if (res.success && res.data) {
        const allLogs = res.data.data || res.data
        if (Array.isArray(allLogs) && allLogs.length > 0) {
          const today = new Date().toISOString().split('T')[0]
          const todayCount = allLogs.filter((l) => l.timestamp?.startsWith(today)).length

          // Count by module
          const moduleCounts: Record<string, number> = {}
          allLogs.forEach((l) => {
            if (l.module) moduleCounts[l.module] = (moduleCounts[l.module] || 0) + 1
          })
          const mostActive = Object.entries(moduleCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'N/A'

          const recentActions = allLogs.slice(0, 3).map((l) => l.action || 'N/A')

          setSummary({
            totalLogs: allLogs.length,
            todayLogs: todayCount,
            mostActiveModule: mostActive,
            recentActions,
          })
        }
      }
    } catch {
      // Ignore summary errors
    } finally {
      setSummaryLoading(false)
    }
  }, [])

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

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Activity Logs</h1>
          <p className="text-muted-foreground mt-1">
            Monitor all system activities and user actions
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant={autoRefresh ? 'default' : 'outline'}
            size="sm"
            onClick={() => setAutoRefresh(!autoRefresh)}
          >
            <ToggleLeft className="size-4" />
            Auto-Refresh
          </Button>
          <Button variant="outline" size="sm" onClick={fetchLogs} disabled={loading}>
            <RefreshCw className={`size-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {summaryLoading ? (
          Array.from({ length: 4 }).map((_, i) => <SummaryCardSkeleton key={i} />)
        ) : (
          <>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400">
                  <ScrollText className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Total Logs</p>
                  <p className="text-lg font-bold truncate">{summary.totalLogs}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                  <Clock className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Today&apos;s Logs</p>
                  <p className="text-lg font-bold truncate">{summary.todayLogs}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-violet-100 text-violet-600 dark:bg-violet-900/30 dark:text-violet-400">
                  <Zap className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Most Active Module</p>
                  <p className="text-lg font-bold truncate">{summary.mostActiveModule}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400">
                  <Activity className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Recent Actions</p>
                  <p className="text-xs font-medium truncate mt-1">
                    {summary.recentActions.length > 0
                      ? summary.recentActions.slice(0, 2).join(', ')
                      : 'None'}
                  </p>
                </div>
              </div>
            </Card>
          </>
        )}
      </div>

      {/* Filter Bar */}
      <Card className="p-4">
        <div className="flex flex-col lg:flex-row gap-3">
          {/* Search */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              placeholder="Search logs..."
              className="pl-9"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
            />
            {searchInput && (
              <Button
                variant="ghost"
                size="icon"
                className="absolute right-1 top-1/2 -translate-y-1/2 size-7"
                onClick={() => setSearchInput('')}
              >
                <X className="size-3" />
              </Button>
            )}
          </div>

          {/* Filters */}
          <div className="flex flex-wrap gap-2">
            <Select value={moduleFilter} onValueChange={(v) => setModuleFilter(v)}>
              <SelectTrigger className="w-[130px]">
                <SelectValue placeholder="Module" />
              </SelectTrigger>
              <SelectContent>
                {MODULE_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Input
              placeholder="Action"
              className="w-[120px]"
              value={actionFilter}
              onChange={(e) => setActionFilter(e.target.value)}
            />

            <Input
              placeholder="User ID"
              className="w-[120px]"
              value={userFilter}
              onChange={(e) => setUserFilter(e.target.value)}
            />

            <Input
              type="date"
              className="w-[140px]"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
            />
            <Input
              type="date"
              className="w-[140px]"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
            />

            <Select value={String(limit)} onValueChange={(v) => setLimit(Number(v))}>
              <SelectTrigger className="w-[80px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="25">25</SelectItem>
                <SelectItem value="50">50</SelectItem>
                <SelectItem value="100">100</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </Card>

      {/* Data Table */}
      <Card>
        <CardContent className="p-0">
          {error ? (
            <div className="flex flex-col items-center justify-center py-16 gap-4">
              <AlertTriangle className="size-12 text-destructive" />
              <p className="text-muted-foreground text-center">{error}</p>
              <Button onClick={fetchLogs} variant="outline">
                Retry
              </Button>
            </div>
          ) : loading ? (
            <div className="p-4">
              <TableSkeleton />
            </div>
          ) : (
            <div>
              {/* Results count */}
              <div className="flex items-center justify-between px-4 py-3 border-b">
                <p className="text-sm text-muted-foreground">
                  Showing {logs.length} of {total} logs
                </p>
                {autoRefresh && (
                  <div className="flex items-center gap-2 text-xs text-muted-foreground">
                    <Loader2 className="size-3 animate-spin" />
                    Auto-refreshing every 15s
                  </div>
                )}
              </div>

              <div className="max-h-[500px] overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="hidden lg:table-cell">Timestamp</TableHead>
                      <TableHead className="lg:hidden">Time</TableHead>
                      <TableHead>User</TableHead>
                      <TableHead>Action</TableHead>
                      <TableHead>Module</TableHead>
                      <TableHead className="hidden md:table-cell">Details</TableHead>
                      <TableHead className="hidden sm:table-cell">IP Address</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {logs.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="h-32 text-center">
                          <div className="flex flex-col items-center gap-2">
                            <ScrollText className="size-8 text-muted-foreground opacity-50" />
                            <p className="text-muted-foreground text-sm">No logs found</p>
                          </div>
                        </TableCell>
                      </TableRow>
                    ) : (
                      logs.map((log) => {
                        const ModuleIcon = moduleIcons[log.module] || FileText
                        return (
                          <TableRow key={log.id}>
                            <TableCell className="hidden lg:table-cell text-xs text-muted-foreground font-mono">
                              {formatTimestamp(log.timestamp)}
                            </TableCell>
                            <TableCell className="lg:hidden text-xs text-muted-foreground font-mono">
                              {log.timestamp
                                ? new Date(log.timestamp).toLocaleString('en-US', {
                                    month: 'short',
                                    day: 'numeric',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                  })
                                : 'N/A'}
                            </TableCell>
                            <TableCell className="font-medium text-sm">
                              <div className="flex items-center gap-1.5">
                                <User className="size-3 text-muted-foreground" />
                                {log.userName || log.userId?.slice(0, 8) || 'N/A'}
                              </div>
                            </TableCell>
                            <TableCell className="text-sm">{log.action || 'N/A'}</TableCell>
                            <TableCell>
                              <Badge
                                variant="secondary"
                                className={moduleBadgeColor[log.module] || ''}
                              >
                                <ModuleIcon className="size-3 mr-1" />
                                {log.module || 'Unknown'}
                              </Badge>
                            </TableCell>
                            <TableCell className="hidden md:table-cell text-xs text-muted-foreground max-w-[200px] truncate">
                              {log.details || 'N/A'}
                            </TableCell>
                            <TableCell className="hidden sm:table-cell text-xs text-muted-foreground font-mono">
                              {log.ipAddress || 'N/A'}
                            </TableCell>
                          </TableRow>
                        )
                      })
                    )}
                  </TableBody>
                </Table>
              </div>

              <div className="px-4">
                <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
