'use client'

import { useState, useMemo } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
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 {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import {
  Download,
  Filter,
  ChevronDown,
  ChevronUp,
  Clock,
  User,
  Activity,
  Database,
  Globe,
  ChevronLeft,
  ChevronRight,
  RefreshCw,
  RotateCcw,
} from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { cn } from '@/lib/utils'

// Action type options
const ACTION_TYPES = [
  'CREATE',
  'UPDATE',
  'DELETE',
  'IMPORT',
  'EXPORT',
  'LOGIN',
  'LOGIN_SUCCESS',
  'LOGIN_FAILED',
  'INVITATION_ACCEPTED',
  'SUBMIT_EVALUATION',
  'EVALUATION_SUBMITTED',
  'UPDATE_STATUS',
  'ROUND_ACTIVATED',
  'ROUND_CLOSED',
  'ROUND_ARCHIVED',
  'UPLOAD_FILE',
  'DELETE_FILE',
  'FILE_DOWNLOADED',
  'BULK_CREATE',
  'BULK_UPDATE_STATUS',
  'UPDATE_EVALUATION_FORM',
  'ROLE_CHANGED',
  'PASSWORD_SET',
  'PASSWORD_CHANGED',
]

// Entity type options
const ENTITY_TYPES = [
  'User',
  'Program',
  'Round',
  'Project',
  'Assignment',
  'Evaluation',
  'EvaluationForm',
  'ProjectFile',
  'GracePeriod',
]

// Color map for action types
const actionColors: Record<string, 'default' | 'destructive' | 'secondary' | 'outline'> = {
  CREATE: 'default',
  UPDATE: 'secondary',
  DELETE: 'destructive',
  IMPORT: 'default',
  EXPORT: 'outline',
  LOGIN: 'outline',
  LOGIN_SUCCESS: 'outline',
  LOGIN_FAILED: 'destructive',
  INVITATION_ACCEPTED: 'default',
  SUBMIT_EVALUATION: 'default',
  EVALUATION_SUBMITTED: 'default',
  ROUND_ACTIVATED: 'default',
  ROUND_CLOSED: 'secondary',
  ROUND_ARCHIVED: 'secondary',
  FILE_DOWNLOADED: 'outline',
  ROLE_CHANGED: 'secondary',
  PASSWORD_SET: 'outline',
  PASSWORD_CHANGED: 'outline',
}

export default function AuditLogPage() {
  // Filter state
  const [filters, setFilters] = useState({
    userId: '',
    action: '',
    entityType: '',
    startDate: '',
    endDate: '',
  })
  const [page, setPage] = useState(1)
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set())
  const [showFilters, setShowFilters] = useState(true)

  // Build query input
  const queryInput = useMemo(
    () => ({
      userId: filters.userId || undefined,
      action: filters.action || undefined,
      entityType: filters.entityType || undefined,
      startDate: filters.startDate ? new Date(filters.startDate) : undefined,
      endDate: filters.endDate
        ? new Date(filters.endDate + 'T23:59:59')
        : undefined,
      page,
      perPage: 50,
    }),
    [filters, page]
  )

  // Fetch audit logs
  const { data, isLoading, refetch } = trpc.audit.list.useQuery(queryInput)

  // Fetch users for filter dropdown
  const { data: usersData } = trpc.user.list.useQuery({
    page: 1,
    perPage: 100,
  })

  // Export mutation
  const exportLogs = trpc.export.auditLogs.useQuery(
    {
      userId: filters.userId || undefined,
      action: filters.action || undefined,
      entityType: filters.entityType || undefined,
      startDate: filters.startDate ? new Date(filters.startDate) : undefined,
      endDate: filters.endDate
        ? new Date(filters.endDate + 'T23:59:59')
        : undefined,
    },
    { enabled: false }
  )

  // Handle export
  const handleExport = async () => {
    const result = await exportLogs.refetch()
    if (result.data) {
      const { data: rows, columns } = result.data

      // Build CSV
      const csvContent = [
        columns.join(','),
        ...rows.map((row) =>
          columns
            .map((col) => {
              const value = row[col as keyof typeof row]
              // Escape quotes and wrap in quotes if contains comma
              if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
                return `"${value.replace(/"/g, '""')}"`
              }
              return value ?? ''
            })
            .join(',')
        ),
      ].join('\n')

      // Download
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `audit-logs-${new Date().toISOString().split('T')[0]}.csv`
      link.click()
      URL.revokeObjectURL(url)
    }
  }

  // Reset filters
  const resetFilters = () => {
    setFilters({
      userId: '',
      action: '',
      entityType: '',
      startDate: '',
      endDate: '',
    })
    setPage(1)
  }

  // Toggle row expansion
  const toggleRow = (id: string) => {
    const newExpanded = new Set(expandedRows)
    if (newExpanded.has(id)) {
      newExpanded.delete(id)
    } else {
      newExpanded.add(id)
    }
    setExpandedRows(newExpanded)
  }

  const hasFilters = Object.values(filters).some((v) => v !== '')

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Audit Logs</h1>
          <p className="text-muted-foreground">
            View system activity and user actions
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="icon" onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            onClick={handleExport}
            disabled={exportLogs.isFetching}
          >
            <Download className="mr-2 h-4 w-4" />
            Export CSV
          </Button>
        </div>
      </div>

      {/* Filters */}
      <Collapsible open={showFilters} onOpenChange={setShowFilters}>
        <Card>
          <CollapsibleTrigger asChild>
            <CardHeader className="cursor-pointer hover:bg-muted/50 transition-colors">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Filter className="h-4 w-4" />
                  <CardTitle className="text-lg">Filters</CardTitle>
                  {hasFilters && (
                    <Badge variant="secondary" className="ml-2">
                      Active
                    </Badge>
                  )}
                </div>
                {showFilters ? (
                  <ChevronUp className="h-4 w-4" />
                ) : (
                  <ChevronDown className="h-4 w-4" />
                )}
              </div>
            </CardHeader>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                {/* User Filter */}
                <div className="space-y-2">
                  <Label>User</Label>
                  <Select
                    value={filters.userId}
                    onValueChange={(v) =>
                      setFilters({ ...filters, userId: v === '__all__' ? '' : v })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="All users" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="__all__">All users</SelectItem>
                      {usersData?.users.map((user) => (
                        <SelectItem key={user.id} value={user.id}>
                          {user.name || user.email}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Action Filter */}
                <div className="space-y-2">
                  <Label>Action</Label>
                  <Select
                    value={filters.action}
                    onValueChange={(v) =>
                      setFilters({ ...filters, action: v === '__all__' ? '' : v })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="All actions" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="__all__">All actions</SelectItem>
                      {ACTION_TYPES.map((action) => (
                        <SelectItem key={action} value={action}>
                          {action.replace(/_/g, ' ')}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Entity Type Filter */}
                <div className="space-y-2">
                  <Label>Entity Type</Label>
                  <Select
                    value={filters.entityType}
                    onValueChange={(v) =>
                      setFilters({ ...filters, entityType: v === '__all__' ? '' : v })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="All types" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="__all__">All types</SelectItem>
                      {ENTITY_TYPES.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Start Date */}
                <div className="space-y-2">
                  <Label>From Date</Label>
                  <Input
                    type="date"
                    value={filters.startDate}
                    onChange={(e) =>
                      setFilters({ ...filters, startDate: e.target.value })
                    }
                  />
                </div>

                {/* End Date */}
                <div className="space-y-2">
                  <Label>To Date</Label>
                  <Input
                    type="date"
                    value={filters.endDate}
                    onChange={(e) =>
                      setFilters({ ...filters, endDate: e.target.value })
                    }
                  />
                </div>
              </div>

              {hasFilters && (
                <div className="flex justify-end">
                  <Button variant="ghost" size="sm" onClick={resetFilters}>
                    <RotateCcw className="mr-2 h-4 w-4" />
                    Reset Filters
                  </Button>
                </div>
              )}
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>

      {/* Results */}
      {isLoading ? (
        <AuditLogSkeleton />
      ) : data && data.logs.length > 0 ? (
        <>
          {/* Desktop Table View */}
          <Card className="hidden md:block">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[180px]">Timestamp</TableHead>
                  <TableHead>User</TableHead>
                  <TableHead>Action</TableHead>
                  <TableHead>Entity</TableHead>
                  <TableHead>IP Address</TableHead>
                  <TableHead className="w-[50px]"></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.logs.map((log) => {
                  const isExpanded = expandedRows.has(log.id)
                  return (
                    <>
                      <TableRow
                        key={log.id}
                        className="cursor-pointer hover:bg-muted/50"
                        onClick={() => toggleRow(log.id)}
                      >
                        <TableCell className="font-mono text-xs">
                          {formatDate(log.timestamp)}
                        </TableCell>
                        <TableCell>
                          <div>
                            <p className="font-medium text-sm">
                              {log.user?.name || 'System'}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {log.user?.email}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant={actionColors[log.action] || 'secondary'}
                          >
                            {log.action.replace(/_/g, ' ')}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div>
                            <p className="text-sm">{log.entityType}</p>
                            {log.entityId && (
                              <p className="text-xs text-muted-foreground font-mono">
                                {log.entityId.slice(0, 8)}...
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="font-mono text-xs">
                          {log.ipAddress || '-'}
                        </TableCell>
                        <TableCell>
                          {isExpanded ? (
                            <ChevronUp className="h-4 w-4" />
                          ) : (
                            <ChevronDown className="h-4 w-4" />
                          )}
                        </TableCell>
                      </TableRow>
                      {isExpanded && (
                        <TableRow key={`${log.id}-details`}>
                          <TableCell colSpan={6} className="bg-muted/30">
                            <div className="p-4 space-y-2">
                              <div className="grid gap-4 sm:grid-cols-2">
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground">
                                    Entity ID
                                  </p>
                                  <p className="font-mono text-sm">
                                    {log.entityId || 'N/A'}
                                  </p>
                                </div>
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground">
                                    User Agent
                                  </p>
                                  <p className="text-sm truncate max-w-md">
                                    {log.userAgent || 'N/A'}
                                  </p>
                                </div>
                              </div>
                              {log.detailsJson && (
                                <div>
                                  <p className="text-xs font-medium text-muted-foreground mb-1">
                                    Details
                                  </p>
                                  <pre className="text-xs bg-muted rounded p-2 overflow-x-auto">
                                    {JSON.stringify(log.detailsJson, null, 2)}
                                  </pre>
                                </div>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                    </>
                  )
                })}
              </TableBody>
            </Table>
          </Card>

          {/* Mobile Card View */}
          <div className="space-y-4 md:hidden">
            {data.logs.map((log) => {
              const isExpanded = expandedRows.has(log.id)
              return (
                <Card
                  key={log.id}
                  className="cursor-pointer"
                  onClick={() => toggleRow(log.id)}
                >
                  <CardHeader className="pb-2">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-2">
                        <Badge
                          variant={actionColors[log.action] || 'secondary'}
                        >
                          {log.action.replace(/_/g, ' ')}
                        </Badge>
                        <span className="text-sm text-muted-foreground">
                          {log.entityType}
                        </span>
                      </div>
                      {isExpanded ? (
                        <ChevronUp className="h-4 w-4" />
                      ) : (
                        <ChevronDown className="h-4 w-4" />
                      )}
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    <div className="flex items-center gap-4 text-sm">
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <Clock className="h-3 w-3" />
                        <span className="text-xs">
                          {formatDate(log.timestamp)}
                        </span>
                      </div>
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <User className="h-3 w-3" />
                        <span className="text-xs">
                          {log.user?.name || 'System'}
                        </span>
                      </div>
                    </div>

                    {isExpanded && (
                      <div className="mt-4 pt-4 border-t space-y-3">
                        <div>
                          <p className="text-xs font-medium text-muted-foreground">
                            Entity ID
                          </p>
                          <p className="font-mono text-xs">
                            {log.entityId || 'N/A'}
                          </p>
                        </div>
                        <div>
                          <p className="text-xs font-medium text-muted-foreground">
                            IP Address
                          </p>
                          <p className="font-mono text-xs">
                            {log.ipAddress || 'N/A'}
                          </p>
                        </div>
                        {log.detailsJson && (
                          <div>
                            <p className="text-xs font-medium text-muted-foreground mb-1">
                              Details
                            </p>
                            <pre className="text-xs bg-muted rounded p-2 overflow-x-auto">
                              {JSON.stringify(log.detailsJson, null, 2)}
                            </pre>
                          </div>
                        )}
                      </div>
                    )}
                  </CardContent>
                </Card>
              )
            })}
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-between">
            <p className="text-sm text-muted-foreground">
              Showing {(page - 1) * 50 + 1} to{' '}
              {Math.min(page * 50, data.total)} of {data.total} results
            </p>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage(page - 1)}
                disabled={page === 1}
              >
                <ChevronLeft className="h-4 w-4" />
                Previous
              </Button>
              <span className="text-sm">
                Page {page} of {data.totalPages}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage(page + 1)}
                disabled={page >= data.totalPages}
              >
                Next
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Activity className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No audit logs found</p>
            <p className="text-sm text-muted-foreground">
              {hasFilters
                ? 'Try adjusting your filters'
                : 'Activity will appear here as users interact with the system'}
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

function AuditLogSkeleton() {
  return (
    <Card>
      <CardContent className="p-6">
        <div className="space-y-4">
          {[...Array(10)].map((_, i) => (
            <div key={i} className="flex items-center gap-4">
              <Skeleton className="h-4 w-32" />
              <Skeleton className="h-4 w-24" />
              <Skeleton className="h-6 w-20" />
              <Skeleton className="h-4 w-16" />
              <Skeleton className="h-4 w-24 ml-auto" />
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}
