'use client'

import { useMemo } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { AlertTriangle, CheckCircle } from 'lucide-react'
import type { ComplianceRequirement } from '@/lib/types/infrastructure'

interface ComplianceGapAnalysisProps {
  requirements: ComplianceRequirement[]
  targetFrameworks?: string[]
}

export function ComplianceGapAnalysis({
  requirements,
  targetFrameworks = ['GDPR', 'PCI-DSS', 'HIPAA', 'SOC 2'],
}: ComplianceGapAnalysisProps) {
  const analysis = useMemo(() => {
    const gaps: Array<{
      country: string
      missingFrameworks: string[]
      status: string
    }> = []

    const frameworkCoverage: Record<string, { total: number; compliant: number }> = {}

    targetFrameworks.forEach((framework) => {
      frameworkCoverage[framework] = { total: 0, compliant: 0 }
    })

    requirements.forEach((req) => {
      const missing = targetFrameworks.filter((f) => !req.frameworks.includes(f))
      if (missing.length > 0) {
        gaps.push({
          country: req.country,
          missingFrameworks: missing,
          status: req.status,
        })
      }

      targetFrameworks.forEach((framework) => {
        frameworkCoverage[framework].total++
        if (req.frameworks.includes(framework)) {
          frameworkCoverage[framework].compliant++
        }
      })
    })

    const overallProgress =
      requirements.length > 0
        ? (requirements.filter((r) => r.status === 'Compliant').length / requirements.length) * 100
        : 0

    return {
      gaps,
      frameworkCoverage,
      overallProgress,
      totalCountries: requirements.length,
      compliantCountries: requirements.filter((r) => r.status === 'Compliant').length,
    }
  }, [requirements, targetFrameworks])

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Overall Compliance Progress</CardTitle>
          <CardDescription>
            {analysis.compliantCountries} of {analysis.totalCountries} countries are fully compliant
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div>
              <div className="flex justify-between text-sm mb-2">
                <span className="text-studio-medium">Progress</span>
                <span className="text-studio-light font-semibold">
                  {analysis.overallProgress.toFixed(1)}%
                </span>
              </div>
              <Progress value={analysis.overallProgress} className="h-2" />
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Framework Coverage</CardTitle>
          <CardDescription>Compliance status by framework</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {Object.entries(analysis.frameworkCoverage).map(([framework, coverage]) => {
              const percentage = coverage.total > 0 ? (coverage.compliant / coverage.total) * 100 : 0
              return (
                <div key={framework}>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium">{framework}</span>
                    <Badge
                      variant={percentage >= 80 ? 'default' : percentage >= 50 ? 'outline' : 'destructive'}
                    >
                      {coverage.compliant}/{coverage.total}
                    </Badge>
                  </div>
                  <Progress value={percentage} className="h-2" />
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Compliance Gaps</CardTitle>
          <CardDescription>
            Countries missing required frameworks ({analysis.gaps.length} found)
          </CardDescription>
        </CardHeader>
        <CardContent>
          {analysis.gaps.length === 0 ? (
            <div className="flex items-center gap-2 text-green-400">
              <CheckCircle className="h-5 w-5" />
              <span>All countries meet the required frameworks</span>
            </div>
          ) : (
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {analysis.gaps.map((gap) => (
                <div
                  key={gap.country}
                  className="p-3 border border-studio-medium rounded-lg flex items-start gap-3"
                >
                  <AlertTriangle className="h-5 w-5 text-yellow-400 mt-0.5" />
                  <div className="flex-1">
                    <div className="font-medium text-studio-light">{gap.country}</div>
                    <div className="text-sm text-studio-medium mt-1">
                      Missing: {gap.missingFrameworks.join(', ')}
                    </div>
                    <Badge className="mt-2" variant="outline">
                      {gap.status}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

