'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Download, Filter } from 'lucide-react'
import type { AuditLogEntry, AuditAction, AuditEntityType } from '@/lib/services/auditLog'

interface AuditLogViewerProps {
  logs: AuditLogEntry[]
  onFilter?: (filters: any) => void
}

export function AuditLogViewer({ logs, onFilter }: AuditLogViewerProps) {
  const [filteredLogs, setFilteredLogs] = useState<AuditLogEntry[]>(logs)
  const [filters, setFilters] = useState<{
    action?: AuditAction
    entityType?: AuditEntityType
    search?: string
  }>({})

  useEffect(() => {
    let filtered = [...logs]

    if (filters.action) {
      filtered = filtered.filter((log) => log.action === filters.action)
    }
    if (filters.entityType) {
      filtered = filtered.filter((log) => log.entityType === filters.entityType)
    }
    if (filters.search) {
      const searchLower = filters.search.toLowerCase()
      filtered = filtered.filter(
        (log) =>
          log.entityName.toLowerCase().includes(searchLower) ||
          log.entityId.toLowerCase().includes(searchLower)
      )
    }

    setFilteredLogs(filtered)
    onFilter?.(filters)
  }, [logs, filters, onFilter])

  const actionColors: Record<AuditAction, string> = {
    create: 'bg-green-500/20 text-green-400',
    update: 'bg-blue-500/20 text-blue-400',
    delete: 'bg-red-500/20 text-red-400',
    export: 'bg-purple-500/20 text-purple-400',
    import: 'bg-orange-500/20 text-orange-400',
    backup: 'bg-yellow-500/20 text-yellow-400',
    restore: 'bg-cyan-500/20 text-cyan-400',
  }

  const exportLogs = () => {
    const csv = [
      ['Timestamp', 'Action', 'Entity Type', 'Entity ID', 'Entity Name', 'User ID'].join(','),
      ...filteredLogs.map((log) =>
        [
          log.timestamp,
          log.action,
          log.entityType,
          log.entityId,
          log.entityName,
          log.userId || '',
        ].join(',')
      ),
    ].join('\n')

    const blob = new Blob([csv], { type: 'text/csv' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `audit-logs-${new Date().toISOString().split('T')[0]}.csv`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>Audit Log</CardTitle>
            <CardDescription>
              Track all changes and operations ({filteredLogs.length} entries)
            </CardDescription>
          </div>
          <Button variant="outline" size="sm" onClick={exportLogs}>
            <Download className="h-4 w-4 mr-2" />
            Export
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-4 mb-4">
          <div className="flex gap-4">
            <Select
              value={filters.action || 'all'}
              onValueChange={(value) =>
                setFilters({ ...filters, action: value === 'all' ? undefined : (value as AuditAction) })
              }
            >
              <SelectTrigger className="w-40">
                <SelectValue placeholder="Action" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Actions</SelectItem>
                <SelectItem value="create">Create</SelectItem>
                <SelectItem value="update">Update</SelectItem>
                <SelectItem value="delete">Delete</SelectItem>
                <SelectItem value="export">Export</SelectItem>
                <SelectItem value="import">Import</SelectItem>
                <SelectItem value="backup">Backup</SelectItem>
                <SelectItem value="restore">Restore</SelectItem>
              </SelectContent>
            </Select>

            <Select
              value={filters.entityType || 'all'}
              onValueChange={(value) =>
                setFilters({
                  ...filters,
                  entityType: value === 'all' ? undefined : (value as AuditEntityType),
                })
              }
            >
              <SelectTrigger className="w-40">
                <SelectValue placeholder="Entity Type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="compliance">Compliance</SelectItem>
                <SelectItem value="milestone">Milestone</SelectItem>
                <SelectItem value="cost">Cost</SelectItem>
                <SelectItem value="topology">Topology</SelectItem>
              </SelectContent>
            </Select>

            <Input
              placeholder="Search..."
              value={filters.search || ''}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="flex-1 max-w-xs"
            />
          </div>
        </div>

        <div className="border border-studio-medium rounded-lg overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Timestamp</TableHead>
                <TableHead>Action</TableHead>
                <TableHead>Entity</TableHead>
                <TableHead>Name</TableHead>
                <TableHead>User</TableHead>
                <TableHead>Changes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredLogs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-studio-medium">
                    No audit log entries found
                  </TableCell>
                </TableRow>
              ) : (
                filteredLogs.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell className="text-sm">
                      {new Date(log.timestamp).toLocaleString()}
                    </TableCell>
                    <TableCell>
                      <Badge className={actionColors[log.action] || ''}>{log.action}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{log.entityType}</Badge>
                    </TableCell>
                    <TableCell className="font-medium">{log.entityName}</TableCell>
                    <TableCell className="text-studio-medium">
                      {log.userId || 'System'}
                    </TableCell>
                    <TableCell>
                      {log.changes ? (
                        <details className="text-xs">
                          <summary className="cursor-pointer text-studio-medium">
                            {Object.keys(log.changes).length} change(s)
                          </summary>
                          <pre className="mt-2 p-2 bg-studio-black rounded text-xs overflow-auto max-h-32">
                            {JSON.stringify(log.changes, null, 2)}
                          </pre>
                        </details>
                      ) : (
                        <span className="text-studio-medium">-</span>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  )
}

