'use client'

import { useState, useMemo, useEffect } from 'react'
import { useQuery } from '@apollo/client'
import LensSelector from './LensSelector'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { getHealthScoreColor, getPillarColor, pillars } from '@/lib/design-system'
import type { PillarCode } from './LensSelector'
import { GET_PILLARS, GET_FINDINGS } from '@/lib/graphql/queries/well-architected'
import { useFindingCreated, useRiskCreated } from '@/lib/graphql/hooks/useSubscriptions'

export default function WAFDashboard() {
  const [selectedLens, setSelectedLens] = useState<PillarCode | null>(null)

  // Fetch pillars
  const { data: pillarsData, loading: pillarsLoading } = useQuery(GET_PILLARS, {
    fetchPolicy: 'cache-and-network',
  })

  // Fetch findings with optional filter by pillar
  const { data: findingsData, loading: findingsLoading, refetch: refetchFindings } = useQuery(GET_FINDINGS, {
    variables: {
      filter: selectedLens
        ? {
            // Filter by pillar code if selected
            // Note: This assumes the filter supports pillar filtering
            // If not, we'll filter client-side
          }
        : undefined,
    },
    fetchPolicy: 'cache-and-network',
  })

  // Real-time subscriptions for new findings and risks
  const { finding: newFinding } = useFindingCreated(selectedLens ? undefined : undefined)
  const { risk: newRisk } = useRiskCreated()

  // Refetch findings when new ones arrive
  useEffect(() => {
    if (newFinding) {
      refetchFindings()
    }
  }, [newFinding, refetchFindings])

  useEffect(() => {
    if (newRisk) {
      // Handle new risk - could show notification or update UI
      refetchFindings()
    }
  }, [newRisk, refetchFindings])

  // Calculate pillar scores from findings
  const pillarScores = useMemo(() => {
    const scores: Record<string, number> = {}
    const findings = findingsData?.findings || []

    Object.keys(pillars).forEach((code) => {
      const pillarFindings = findings.filter(
        (f: any) => f.control?.pillar?.code === code
      )
      
      if (pillarFindings.length === 0) {
        scores[code] = 100 // No findings = perfect score
      } else {
        const passed = pillarFindings.filter((f: any) => f.status === 'PASS').length
        const total = pillarFindings.length
        scores[code] = Math.round((passed / total) * 100)
      }
    })

    return scores
  }, [findingsData])

  // Filter findings by selected lens
  const filteredFindings = useMemo(() => {
    const findings = findingsData?.findings || []
    if (!selectedLens) return findings
    
    return findings.filter((f: any) => f.control?.pillar?.code === selectedLens)
  }, [findingsData, selectedLens])

  if (pillarsLoading || findingsLoading) {
    return (
      <div className="space-y-6 p-6">
        <h1 className="text-3xl font-bold text-white">Well-Architected Framework</h1>
        <div className="text-white">Loading...</div>
      </div>
    )
  }

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold text-white">Well-Architected Framework</h1>
        <LensSelector selectedLens={selectedLens} onLensChange={setSelectedLens} />
      </div>

      <div className="grid gap-6 md:grid-cols-3 lg:grid-cols-6">
        {Object.entries(pillars).map(([code, pillar]) => {
          const score = pillarScores[code] ?? 100
          const color = getHealthScoreColor(score)
          
          return (
            <Card key={code}>
              <CardHeader>
                <CardTitle 
                  className="text-sm" 
                  data-pillar-color
                  style={{ '--pillar-color': getPillarColor(code as PillarCode) } as React.CSSProperties}
                >
                  {pillar.name}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div 
                  className="text-3xl font-bold" 
                  data-score-color
                  style={{ '--score-color': color } as React.CSSProperties}
                >
                  {score}%
                </div>
              </CardContent>
            </Card>
          )
        })}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Findings</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredFindings.length === 0 ? (
            <div className="text-white">No findings available</div>
          ) : (
            <div className="space-y-4">
              {filteredFindings.map((finding: any) => (
                <div
                  key={finding.id}
                  className="rounded-lg border border-studio-medium bg-studio-dark p-4"
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-semibold text-white">{finding.title}</h3>
                      <p className="text-sm text-gray-400">
                        {finding.control?.code || 'UNKNOWN'} • {finding.resource?.name || 'Unknown Resource'}
                      </p>
                      {finding.description && (
                        <p className="text-sm text-gray-500 mt-1">{finding.description}</p>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      <span
                        className={`rounded px-2 py-1 text-xs font-semibold ${
                          finding.status === 'PASS'
                            ? 'status-pass'
                            : finding.status === 'WARNING'
                            ? 'status-warning'
                            : 'status-fail'
                        }`}
                      >
                        {finding.status}
                      </span>
                      <span className="text-xs text-gray-400">{finding.severity}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

