import { ReactNode, useState } from "react"
import { 
  BookOpen, 
  Save, 
  RotateCcw, 
  Loader2,
  ExternalLink,
  AlertCircle,
  Crown as CrownIcon
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { cn } from "@/lib/utils"
import { usePro } from "@/contexts/pro-context"

export interface FeatureHeaderProps {
  /** Icon component to display */
  icon: ReactNode
  /** Feature title */
  title: string
  /** Feature description */
  description: string
  /** Documentation URL - opens in new tab */
  documentationUrl: string
  /** Whether the feature is enabled */
  enabled: boolean
  /** Callback when enabled state changes */
  onEnabledChange: (enabled: boolean) => void
  /** Whether there are unsaved changes */
  hasChanges: boolean
  /** Whether save is in progress */
  isSaving: boolean
  /** Callback to save settings */
  onSave: () => void
  /** Callback to reset settings to defaults */
  onReset: () => void
  /** Optional: Custom save button text */
  saveButtonText?: string
  /** Optional: Custom reset confirmation message */
  resetConfirmMessage?: string
  /** Optional: Additional actions to render before the main actions */
  additionalActions?: ReactNode
  /** Optional: Content to render below the header (will show disabled overlay when disabled) */
  children?: ReactNode
  /** Optional: Whether this feature has Pro-only content (shows upgrade button) */
  hasProFeatures?: boolean
}

export function FeatureHeader({
  icon,
  title,
  description,
  documentationUrl,
  enabled,
  onEnabledChange,
  hasChanges,
  isSaving,
  onSave,
  onReset,
  saveButtonText = "Save Changes",
  resetConfirmMessage = "This will reset all settings for this feature to their default values. Any unsaved changes will be lost.",
  additionalActions,
  children,
  hasProFeatures = true,
}: FeatureHeaderProps) {
  const [resetDialogOpen, setResetDialogOpen] = useState(false)
  const { isPro, upgradeUrl, shakeUpgradeButton } = usePro()

  const handleReset = () => {
    onReset()
    setResetDialogOpen(false)
  }

  const handleDocumentationClick = () => {
    window.open(documentationUrl, '_blank', 'noopener,noreferrer')
  }

  const handleUpgradeClick = () => {
    window.open(upgradeUrl, '_blank', 'noopener,noreferrer')
  }

  // Show upgrade button if feature has Pro features and user is not Pro
  const showUpgradeButton = hasProFeatures && !isPro

  return (
    <div className="flex flex-1 flex-col">
      {/* Sticky Header */}
      <div className="sticky top-16 z-40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b">
        <div className="flex flex-col gap-4 p-6 pb-4">
          {/* Top Row: Icon, Title, Description + Actions */}
          <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            {/* Left side: Icon + Title + Description */}
            <div className="flex items-start gap-4">
              <div className={cn(
                "flex h-12 w-12 shrink-0 items-center justify-center rounded-lg text-white transition-colors mt-0.5",
                enabled ? "bg-primary" : "bg-zinc-400"
              )}>
                {icon}
              </div>
              <div className="min-w-0">
                <div className="flex items-center gap-2">
                  <h1 className={cn(
                    "text-2xl font-bold tracking-tight truncate transition-colors",
                    !enabled && "text-muted-foreground"
                  )}>{title}</h1>
                  {!enabled && (
                    <span className="inline-flex items-center rounded-md bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-inset ring-yellow-600/20">
                      Disabled
                    </span>
                  )}
                </div>
                <p className="text-sm text-muted-foreground line-clamp-1">
                  {description}
                </p>
                {/* Unsaved Changes Indicator - below description, always rendered to prevent layout shift */}
                <div className={cn(
                  "flex items-center gap-2 text-sm text-amber-600 dark:text-amber-500 mt-1 h-5 transition-opacity duration-200",
                  hasChanges ? "opacity-100" : "opacity-0 pointer-events-none"
                )}>
                  <div className="h-2 w-2 rounded-full bg-amber-500 animate-pulse" />
                  <span>You have unsaved changes</span>
                </div>
              </div>
            </div>

            {/* Right side: Action buttons */}
            <div className="flex flex-wrap items-center gap-2 lg:gap-3">
              {/* Additional actions slot */}
              {additionalActions}

            {/* Upgrade to Pro Button - shown when feature has Pro content */}
            {showUpgradeButton && (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      size="sm"
                      onClick={handleUpgradeClick}
                      className={cn(
                        "gap-2 text-white border-0 hover:opacity-90",
                        shakeUpgradeButton && "animate-shake"
                      )}
                      style={{ backgroundColor: '#002269' }}
                    >
                      <CrownIcon className="h-4 w-4" />
                      <span className="hidden sm:inline">Upgrade to Pro</span>
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Unlock Pro features</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            )}

            {/* Documentation Button */}
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleDocumentationClick}
                    className="gap-2"
                  >
                    <BookOpen className="h-4 w-4" />
                    <span className="hidden sm:inline">Docs</span>
                    <ExternalLink className="h-3 w-3 hidden sm:inline" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>View documentation</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>

            {/* Reset Button with Confirmation Dialog */}
            <AlertDialog open={resetDialogOpen} onOpenChange={setResetDialogOpen}>
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <AlertDialogTrigger asChild>
                      <Button
                        variant="outline"
                        size="sm"
                        className="gap-2"
                      >
                        <RotateCcw className="h-4 w-4" />
                        <span className="hidden sm:inline">Reset</span>
                      </Button>
                    </AlertDialogTrigger>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Reset to default settings</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Reset to Default Settings?</AlertDialogTitle>
                  <AlertDialogDescription>
                    {resetConfirmMessage}
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction onClick={handleReset}>
                    Reset Settings
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>

            <Separator orientation="vertical" className="h-8 hidden sm:block" />

            {/* Save Button */}
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    size="sm"
                    onClick={onSave}
                    disabled={isSaving || !hasChanges}
                    className="gap-2"
                  >
                    {isSaving ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin" />
                        <span className="hidden sm:inline">Saving...</span>
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4" />
                        <span className="hidden sm:inline">{saveButtonText}</span>
                      </>
                    )}
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>{hasChanges ? "Save your changes" : "No changes to save"}</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>

            <Separator orientation="vertical" className="h-8 hidden sm:block" />

            {/* Enable/Disable Toggle */}
            <div className={cn(
              "flex items-center gap-2 rounded-lg border px-3 py-1.5 transition-colors",
              enabled ? "bg-background" : "bg-yellow-50 border-yellow-200"
            )}>
              <Switch
                id="feature-enabled"
                checked={enabled}
                onCheckedChange={onEnabledChange}
              />
              <Label 
                htmlFor="feature-enabled" 
                className={cn(
                  "font-medium cursor-pointer text-sm whitespace-nowrap",
                  !enabled && "text-yellow-800"
                )}
              >
                {enabled ? 'Enabled' : 'Disabled'}
              </Label>
            </div>
            </div>
          </div>
        </div>
      </div>

      {/* Content Area with Disabled Overlay */}
      {children && (
        <div className="relative flex-1">
          {/* Disabled State Overlay */}
          {!enabled && (
            <div className="absolute inset-0 z-10 bg-background/80 backdrop-blur-[1px] flex items-start justify-center pt-20">
              <div className="flex flex-col items-center gap-3 text-center max-w-md px-4">
                <div className="flex h-12 w-12 items-center justify-center rounded-full bg-yellow-100">
                  <AlertCircle className="h-6 w-6 text-yellow-600" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-foreground">Feature Disabled</h3>
                  <p className="text-sm text-muted-foreground mt-1">
                    This feature is currently disabled. Enable it using the toggle above to access and configure settings.
                  </p>
                </div>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => onEnabledChange(true)}
                  className="mt-2"
                >
                  Enable {title}
                </Button>
              </div>
            </div>
          )}
          
          {/* Actual Content */}
          <div className={cn(
            "p-6 transition-opacity duration-200",
            !enabled && "opacity-40 pointer-events-none select-none"
          )}>
            {children}
          </div>
        </div>
      )}
    </div>
  )
}
