'use client'

import { useState, useMemo, useEffect } from 'react'
import { AdvancedFilters } from './AdvancedFilters'
import { AuditLogViewer } from './AuditLogViewer'
import { auditLogService } from '@/lib/services/auditLog'
import { useComplianceRequirements } from '@/lib/hooks/useInfrastructureData'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { RegionSelector } from './RegionSelector'
import { EditModeToggle } from './EditModeToggle'
import { EditComplianceForm } from './forms/EditComplianceForm'
import { ComplianceMapView } from './lazy'
import { EmptyState } from './EmptyState'
import { SkeletonTable } from './SkeletonCard'
import { BulkActions } from './BulkActions'
import { ConfirmDialog } from './ConfirmDialog'
import { ComplianceGapAnalysis } from './lazy'
import { Download, Search } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import type { ComplianceRequirement } from '@/lib/types/infrastructure'

const statusColors: Record<string, string> = {
  Compliant: 'bg-green-500/20 text-green-400',
  Partial: 'bg-yellow-500/20 text-yellow-400',
  Pending: 'bg-blue-500/20 text-blue-400',
  'Non-Compliant': 'bg-red-500/20 text-red-400',
}

export function ComplianceMapping() {
  const [selectedRegion, setSelectedRegion] = useState<string>('All')
  const [selectedStatus, setSelectedStatus] = useState<string>('All')
  const [searchQuery, setSearchQuery] = useState('')
  const [editMode, setEditMode] = useState(false)
  const [editingRequirement, setEditingRequirement] = useState<ComplianceRequirement | null>(null)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set())
  const [confirmBulkDelete, setConfirmBulkDelete] = useState(false)
  const [showAuditLog, setShowAuditLog] = useState(false)
  const [auditLogs, setAuditLogs] = useState<any[]>([])
  const { toast } = useToast()

  useEffect(() => {
    if (showAuditLog) {
      const logs = auditLogService.getLogs({ entityType: 'compliance' })
      setAuditLogs(logs)
    }
  }, [showAuditLog])

  const filter = {
    region: selectedRegion === 'All' ? undefined : selectedRegion,
    status: selectedStatus === 'All' ? undefined : selectedStatus,
  }

  const { requirements, loading, error } = useComplianceRequirements(filter)

  const filteredRequirements = useMemo(
    () =>
      requirements.filter((req) =>
        searchQuery
          ? req.country.toLowerCase().includes(searchQuery.toLowerCase()) ||
            req.frameworks.some((f) => f.toLowerCase().includes(searchQuery.toLowerCase()))
          : true
      ),
    [requirements, searchQuery]
  )

  const handleExportCSV = () => {
    const headers = ['Country', 'Region', 'Frameworks', 'Status', 'Requirements', 'Last Audit']
    const rows = filteredRequirements.map((req) => [
      req.country,
      req.region,
      req.frameworks.join('; '),
      req.status,
      req.requirements.join('; '),
      req.lastAuditDate || 'N/A',
    ])

    const csv = [headers, ...rows].map((row) => row.map((cell) => `"${cell}"`).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 = `compliance-requirements-${new Date().toISOString().split('T')[0]}.csv`
    a.click()
    URL.revokeObjectURL(url)
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-studio-light">Compliance Mapping</h1>
          <p className="text-studio-medium mt-2">
            Track compliance requirements by country and framework
          </p>
        </div>
        <Card>
          <CardHeader>
            <SkeletonTable rows={5} />
          </CardHeader>
        </Card>
      </div>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Error Loading Compliance Data</CardTitle>
          <CardDescription>{error.message}</CardDescription>
        </CardHeader>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-studio-light">Compliance Mapping</h1>
          <p className="text-studio-medium mt-2">
            Track compliance requirements by country and framework
          </p>
        </div>
        <Button variant="outline" onClick={handleExportCSV}>
          <Download className="h-4 w-4 mr-2" />
          Export CSV
        </Button>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Compliance Requirements</CardTitle>
              <CardDescription>
                {filteredRequirements.length} requirement{filteredRequirements.length !== 1 ? 's' : ''} found
              </CardDescription>
            </div>
            <div className="flex items-center gap-4">
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-studio-medium" />
                <Input
                  placeholder="Search countries or frameworks..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8 w-64"
                />
              </div>
              <RegionSelector
                value={selectedRegion}
                onChange={setSelectedRegion}
                className="w-48"
              />
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value)}
                className="h-10 rounded-md border border-studio-medium bg-studio-dark px-3 text-sm"
              >
                <option value="All">All Status</option>
                <option value="Compliant">Compliant</option>
                <option value="Partial">Partial</option>
                <option value="Pending">Pending</option>
                <option value="Non-Compliant">Non-Compliant</option>
              </select>
              <EditModeToggle enabled={editMode} onToggle={setEditMode} />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {editMode && selectedItems.size > 0 && (
            <BulkActions
              selectedCount={selectedItems.size}
              onBulkDelete={() => setConfirmBulkDelete(true)}
            />
          )}
          <Table>
            <TableHeader>
              <TableRow>
                {editMode && (
                  <TableHead className="w-12">
                    <Checkbox
                      checked={selectedItems.size === filteredRequirements.length && filteredRequirements.length > 0}
                      onCheckedChange={(checked) => {
                        if (checked) {
                          setSelectedItems(new Set(filteredRequirements.map((r) => r.country)))
                        } else {
                          setSelectedItems(new Set())
                        }
                      }}
                    />
                  </TableHead>
                )}
                <TableHead>Country</TableHead>
                <TableHead>Region</TableHead>
                <TableHead>Frameworks</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Requirements</TableHead>
                <TableHead>Last Audit</TableHead>
                {editMode && <TableHead>Actions</TableHead>}
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredRequirements.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={editMode ? 8 : 6} className="text-center">
                    <EmptyState
                      title="No compliance requirements found"
                      description="Try adjusting your filters or search query."
                      action={
                        editMode
                          ? {
                              label: 'Add Requirement',
                              onClick: () => {
                                // TODO: Add create functionality
                              },
                            }
                          : undefined
                      }
                    />
                  </TableCell>
                </TableRow>
              ) : (
                filteredRequirements.map((req) => (
                  <TableRow key={req.country}>
                    {editMode && (
                      <TableCell>
                        <Checkbox
                          checked={selectedItems.has(req.country)}
                          onCheckedChange={(checked) => {
                            const newSet = new Set(selectedItems)
                            if (checked) {
                              newSet.add(req.country)
                            } else {
                              newSet.delete(req.country)
                            }
                            setSelectedItems(newSet)
                          }}
                        />
                      </TableCell>
                    )}
                    <TableCell className="font-medium">{req.country}</TableCell>
                    <TableCell>{req.region}</TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {req.frameworks.map((framework) => (
                          <Badge key={framework} variant="outline" className="text-xs">
                            {framework}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={statusColors[req.status] || ''}>{req.status}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-md truncate" title={req.requirements.join(', ')}>
                        {req.requirements.length} requirement{req.requirements.length !== 1 ? 's' : ''}
                      </div>
                    </TableCell>
                    <TableCell>
                      {req.lastAuditDate
                        ? new Date(req.lastAuditDate).toLocaleDateString()
                        : 'N/A'}
                    </TableCell>
                    {editMode && (
                      <TableCell>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setEditingRequirement(req)
                            setDialogOpen(true)
                          }}
                        >
                          Edit
                        </Button>
                      </TableCell>
                    )}
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Map view */}
      <Card>
        <CardHeader>
          <CardTitle>Geographic View</CardTitle>
          <CardDescription>Interactive map showing compliance status by country</CardDescription>
        </CardHeader>
        <CardContent>
          {filteredRequirements.length > 0 ? (
            <ComplianceMapView
              requirements={filteredRequirements}
              onCountryClick={(country) => {
                setSearchQuery(country)
              }}
            />
          ) : (
            <EmptyState
              title="No compliance data"
              description="No compliance requirements match your current filters."
            />
          )}
        </CardContent>
      </Card>

      {filteredRequirements.length > 0 && (
        <ComplianceGapAnalysis requirements={filteredRequirements} />
      )}

      {editingRequirement && (
        <EditComplianceForm
          open={dialogOpen}
          onOpenChange={setDialogOpen}
          requirement={editingRequirement}
          onSuccess={() => {
            setEditingRequirement(null)
          }}
        />
      )}

      <ConfirmDialog
        open={confirmBulkDelete}
        onOpenChange={setConfirmBulkDelete}
        title="Delete Selected Items"
        description={`Are you sure you want to delete ${selectedItems.size} compliance requirement(s)? This action cannot be undone.`}
        confirmLabel="Delete"
        variant="destructive"
        onConfirm={() => {
          // TODO: Implement bulk delete
          selectedItems.forEach((country) => {
            auditLogService.log({
              action: 'delete',
              entityType: 'compliance',
              entityId: country,
              entityName: country,
            })
          })
          setSelectedItems(new Set())
          toast({
            title: 'Deleted',
            description: `${selectedItems.size} item(s) deleted`,
          })
        }}
      />

      {showAuditLog && (
        <AuditLogViewer
          logs={auditLogs}
          onFilter={(filters) => {
            const logs = auditLogService.getLogs(filters)
            setAuditLogs(logs)
          }}
        />
      )}
    </div>
  )
}

