import { useState } from 'react'
import { X, Check, SkipForward, Sparkles, ChevronDown, ChevronUp } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { AIFixProposal } from '@/types'
import { Button } from '@/components/ui/Button'

interface AIFixReviewModalProps {
  fixes: AIFixProposal[]
  onApply: (fix: AIFixProposal) => void
  onApplyAll: () => void
  onClose: () => void
}

export function AIFixReviewModal({ fixes, onApply, onApplyAll, onClose }: AIFixReviewModalProps) {
  const [appliedIds, setAppliedIds] = useState<Set<string>>(new Set())
  const [skippedIds, setSkippedIds] = useState<Set<string>>(new Set())
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set(fixes.map(f => f.target_node_id)))

  const handleApply = (fix: AIFixProposal) => {
    onApply(fix)
    setAppliedIds(prev => new Set(prev).add(fix.target_node_id))
  }

  const handleSkip = (fix: AIFixProposal) => {
    setSkippedIds(prev => new Set(prev).add(fix.target_node_id))
  }

  const toggleExpanded = (id: string) => {
    setExpandedIds(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const pendingFixes = fixes.filter(
    f => !appliedIds.has(f.target_node_id) && !skippedIds.has(f.target_node_id)
  )
  const allHandled = pendingFixes.length === 0

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4">
      <div className="relative flex h-[80vh] w-full max-w-2xl flex-col bg-[#14161d] border border-[#1e2130] rounded-2xl shadow-lg">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-[#1e2130] px-6 py-4">
          <div className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-[#22d3ee]" />
            <h2 className="text-lg font-semibold text-[#e2e5eb]">
              AI Fix Proposals ({fixes.length})
            </h2>
          </div>
          <button
            onClick={onClose}
            className="rounded-md p-1 text-[#848b9b] hover:bg-accent hover:text-[#e2e5eb]"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {fixes.map((fix) => {
            const isApplied = appliedIds.has(fix.target_node_id)
            const isSkipped = skippedIds.has(fix.target_node_id)
            const isExpanded = expandedIds.has(fix.target_node_id)

            return (
              <div
                key={fix.target_node_id}
                className={cn(
                  'rounded-lg border p-4',
                  isApplied
                    ? 'border-emerald-400/30 bg-emerald-400/5'
                    : isSkipped
                      ? 'border-[#1e2130] bg-accent/30 opacity-60'
                      : 'border-[#1e2130] bg-[#14161d]'
                )}
              >
                {/* Fix header */}
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1">
                    <p className="text-sm text-red-400 mb-1">{fix.error_message}</p>
                    <p className="text-sm text-[#e2e5eb]">{fix.description}</p>
                    <p className="text-xs text-[#848b9b] mt-1">
                      Node: {fix.target_node_id}
                    </p>
                  </div>
                  {isApplied && (
                    <span className="flex items-center gap-1 rounded-full bg-emerald-400/10 px-2 py-1 text-xs text-emerald-400">
                      <Check className="h-3 w-3" /> Applied
                    </span>
                  )}
                  {isSkipped && (
                    <span className="text-xs text-[#848b9b]">Skipped</span>
                  )}
                </div>

                {/* Expand/collapse detail */}
                {!isApplied && !isSkipped && (
                  <>
                    <button
                      onClick={() => toggleExpanded(fix.target_node_id)}
                      className="mt-2 flex items-center gap-1 text-xs text-[#848b9b] hover:text-[#e2e5eb]"
                    >
                      {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
                      {isExpanded ? 'Hide' : 'Show'} details
                    </button>

                    {isExpanded && (
                      <div className="mt-3 grid grid-cols-2 gap-3">
                        <div>
                          <p className="text-xs font-medium text-[#848b9b] mb-1">Before</p>
                          <pre className="overflow-x-auto rounded bg-accent/50 p-2 text-xs text-[#848b9b] max-h-48 overflow-y-auto">
                            {JSON.stringify(fix.original_node, null, 2)}
                          </pre>
                        </div>
                        <div>
                          <p className="text-xs font-medium text-emerald-400 mb-1">After</p>
                          <pre className="overflow-x-auto rounded bg-emerald-400/5 p-2 text-xs text-[#e2e5eb] max-h-48 overflow-y-auto">
                            {JSON.stringify(fix.fixed_node, null, 2)}
                          </pre>
                        </div>
                      </div>
                    )}

                    {/* Action buttons */}
                    <div className="mt-3 flex gap-2">
                      <Button
                        size="sm"
                        onClick={() => handleApply(fix)}
                      >
                        <Check className="h-3 w-3" />
                        Apply
                      </Button>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => handleSkip(fix)}
                      >
                        <SkipForward className="h-3 w-3" />
                        Skip
                      </Button>
                    </div>
                  </>
                )}
              </div>
            )
          })}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between border-t border-[#1e2130] px-6 py-4">
          <Button variant="secondary" onClick={onClose}>
            {allHandled ? 'Done' : 'Cancel'}
          </Button>
          {!allHandled && (
            <Button onClick={onApplyAll}>
              Apply All ({pendingFixes.length})
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}
