import { useEffect } from 'react'
import { Link } from 'react-router-dom'
import {
  X,
  GitBranch,
  Terminal,
  Layers,
  BarChart3,
  ShieldCheck,
  CheckCircle2,
  Package,
  ChevronRight,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import type { PublicFlowDetail, PublicScriptDetail } from '@/types'

type TemplateDetailModalProps =
  | {
      type: 'flow'
      template: PublicFlowDetail
      onClose: () => void
    }
  | {
      type: 'script'
      template: PublicScriptDetail
      onClose: () => void
    }

const complexityColors: Record<string, string> = {
  basic: 'text-emerald-400',
  intermediate: 'text-amber-400',
  advanced: 'text-rose-500',
}

export function TemplateDetailModal(props: TemplateDetailModalProps) {
  const { type, template, onClose } = props

  // Close on Escape
  useEffect(() => {
    function handleKey(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [onClose])

  // Prevent body scroll while modal is open
  useEffect(() => {
    document.body.style.overflow = 'hidden'
    return () => {
      document.body.style.overflow = ''
    }
  }, [])

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/60" />

      {/* Modal */}
      <div
        className="card-flat relative w-full max-w-2xl max-h-[85vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-start justify-between gap-4 p-6 border-b border-border">
          <div className="flex items-center gap-3 min-w-0">
            {type === 'flow' ? (
              <GitBranch className="w-5 h-5 text-primary shrink-0" />
            ) : (
              <Terminal className="w-5 h-5 text-primary shrink-0" />
            )}
            <div className="min-w-0">
              <h2 className="font-heading text-foreground text-xl font-semibold leading-tight flex items-center gap-2">
                {template.name}
                {type === 'script' && (template as PublicScriptDetail).is_verified && (
                  <CheckCircle2 className="w-4 h-4 text-primary shrink-0" />
                )}
              </h2>
              <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mt-1">
                {type === 'flow' ? 'Flow Template' : 'Script Template'}
              </p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-[rgba(255,255,255,0.04)] transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {template.description && (
            <p className="text-muted-foreground text-sm leading-relaxed">
              {template.description}
            </p>
          )}

          {/* Metadata */}
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
            {type === 'flow' && (
              <>
                <MetaStat
                  label="Steps"
                  value={String((template as PublicFlowDetail).step_count)}
                  icon={<Layers className="w-4 h-4" />}
                />
                {(template as PublicFlowDetail).success_rate !== null && (
                  <MetaStat
                    label="Success Rate"
                    value={`${Math.round((template as PublicFlowDetail).success_rate!)}%`}
                    icon={<BarChart3 className="w-4 h-4" />}
                    valueClassName={
                      (template as PublicFlowDetail).success_rate! >= 80
                        ? 'text-emerald-400'
                        : (template as PublicFlowDetail).success_rate! >= 50
                          ? 'text-amber-400'
                          : 'text-rose-500'
                    }
                  />
                )}
                <MetaStat
                  label="Uses"
                  value={(template as PublicFlowDetail).usage_count.toLocaleString()}
                />
              </>
            )}
            {type === 'script' && (
              <>
                {(template as PublicScriptDetail).complexity && (
                  <MetaStat
                    label="Complexity"
                    value={(template as PublicScriptDetail).complexity!}
                    valueClassName={
                      complexityColors[(template as PublicScriptDetail).complexity!] ||
                      'text-foreground'
                    }
                  />
                )}
                <MetaStat
                  label="Uses"
                  value={(template as PublicScriptDetail).usage_count.toLocaleString()}
                />
                {(template as PublicScriptDetail).requires_elevation && (
                  <MetaStat
                    label="Elevation"
                    value="Required"
                    icon={<ShieldCheck className="w-4 h-4 text-amber-400" />}
                  />
                )}
              </>
            )}
          </div>

          {/* Tags */}
          {template.tags.length > 0 && (
            <div>
              <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-2">
                Tags
              </h4>
              <div className="flex flex-wrap gap-1.5">
                {template.tags.map((tag) => (
                  <span
                    key={tag}
                    className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] px-2 py-0.5 rounded-md bg-card border border-border text-muted-foreground"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Flow preview structure */}
          {type === 'flow' && (template as PublicFlowDetail).preview_structure && (
            <div>
              <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-2">
                Flow Preview
              </h4>
              <div className="bg-card border border-border rounded-xl p-4">
                <PreviewTree structure={(template as PublicFlowDetail).preview_structure!} />
              </div>
            </div>
          )}

          {/* Script parameters */}
          {type === 'script' && (template as PublicScriptDetail).parameters.length > 0 && (
            <div>
              <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-2">
                Parameters
              </h4>
              <div className="space-y-2">
                {(template as PublicScriptDetail).parameters.map((param) => (
                  <div
                    key={param.name}
                    className="flex items-start gap-3 bg-card border border-border rounded-xl p-3"
                  >
                    <code className="font-sans text-xs text-primary shrink-0">
                      {param.name}
                    </code>
                    <span className="text-muted-foreground text-sm flex-1">
                      {param.description}
                    </span>
                    <span className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-text-muted shrink-0">
                      {param.type}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Script modules */}
          {type === 'script' && (template as PublicScriptDetail).requires_modules.length > 0 && (
            <div>
              <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-2">
                Required Modules
              </h4>
              <div className="flex flex-wrap gap-1.5">
                {(template as PublicScriptDetail).requires_modules.map((mod) => (
                  <span
                    key={mod}
                    className="font-sans text-xs text-[0.625rem] px-2 py-0.5 rounded-md bg-card border border-border text-muted-foreground flex items-center gap-1"
                  >
                    <Package className="w-3 h-3" />
                    {mod}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between gap-4 p-6 border-t border-border">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2.5 rounded-lg text-sm font-medium bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-foreground hover:border-[rgba(255,255,255,0.12)] transition-colors"
          >
            Close
          </button>
          <Link
            to="/register"
            className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-semibold bg-primary text-white hover:brightness-110 active:scale-[0.98] transition-all"
          >
            Sign Up to Use This
            <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      </div>
    </div>
  )
}

function MetaStat({
  label,
  value,
  icon,
  valueClassName,
}: {
  label: string
  value: string
  icon?: React.ReactNode
  valueClassName?: string
}) {
  return (
    <div className="bg-card border border-border rounded-xl p-3">
      <div className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-1">
        {label}
      </div>
      <div className={cn('text-foreground text-sm font-semibold flex items-center gap-1.5', valueClassName)}>
        {icon}
        {value}
      </div>
    </div>
  )
}

/**
 * Renders a simplified nested list from the preview_structure object.
 * Expected shape: { name: string, children?: Array<...> }
 */
function PreviewTree({ structure }: { structure: Record<string, unknown> }) {
  const name = (structure.name as string) || (structure.title as string) || 'Root'
  const children = (structure.children as Array<Record<string, unknown>>) || []

  return (
    <div className="text-sm">
      <div className="flex items-center gap-2 text-foreground">
        <ChevronRight className="w-3.5 h-3.5 text-primary" />
        <span>{name}</span>
      </div>
      {children.length > 0 && (
        <div className="ml-5 mt-1 space-y-1 border-l border-border pl-3">
          {children.slice(0, 8).map((child, i) => (
            <PreviewTree key={i} structure={child} />
          ))}
          {children.length > 8 && (
            <span className="text-muted-foreground text-xs">
              +{children.length - 8} more steps...
            </span>
          )}
        </div>
      )}
    </div>
  )
}
