import React, { useState } from "react";
import { Search, Shield, Eye, Lock, LucideIcon } from "lucide-react";
import {
  Badge,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Separator,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
  cn,
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "ikoncomponents";

// ── Types ────────────────────────────────────────────────────────────────────

export type RiskStatus =
  | "identified"
  | "mitigation_planned"
  | "monitoring"
  | "closed";

interface Stage {
  id:    RiskStatus;
  label: string;
  icon:  LucideIcon;
}

interface NavRule {
  canProceed: RiskStatus[];
  canGoBack:  RiskStatus[];
}

interface StatusConfig {
  hex: string;
}

interface RiskWorkflowProps {
  value?:         RiskStatus;
  initialStatus?: RiskStatus;
  onChange?:      (status: RiskStatus) => void;
  standalone?:    boolean;
}

// ── Data ─────────────────────────────────────────────────────────────────────

const STAGES: Stage[] = [
  { id: "identified",         label: "Identified",         icon: Search },
  { id: "mitigation_planned", label: "Mitigation Planned", icon: Shield },
  { id: "monitoring",         label: "Monitoring",         icon: Eye    },
  { id: "closed",             label: "Closed",             icon: Lock   },
];

const NAV_RULES: Record<RiskStatus, NavRule> = {
  identified:         { canProceed: ["mitigation_planned"], canGoBack: []                                   },
  mitigation_planned: { canProceed: ["monitoring"],         canGoBack: ["identified"]                       },
  monitoring:         { canProceed: ["closed"],             canGoBack: ["mitigation_planned", "identified"] },
  closed:             { canProceed: [],                     canGoBack: []                                   },
};

const STATUS_CONFIG: Record<RiskStatus, StatusConfig> = {
  identified:         { hex: "#818cf8" },
  mitigation_planned: { hex: "#fbbf24" },
  monitoring:         { hex: "#60a5fa" },
  closed:             { hex: "#4ade80" },
};

const STAGE_IDS = STAGES.map((s) => s.id);

function getLabel(id: RiskStatus): string {
  return STAGES.find((s) => s.id === id)?.label ?? id;
}

// ── StageNode ─────────────────────────────────────────────────────────────────

interface StageNodeProps {
  stage:       Stage;
  isActive:    boolean;
  isCompleted: boolean;
  cfg:         StatusConfig;
  isClickable: boolean;
  onClickNode: () => void;
  tooltipText: string;
}

function StageNode({
  stage,
  isActive,
  isCompleted,
  cfg,
  isClickable,
  onClickNode,
  tooltipText,
}: StageNodeProps) {
  const Icon = stage.icon;

  const circleStyle: React.CSSProperties = isActive
    ? {
        borderColor:     cfg.hex,
        backgroundColor: `${cfg.hex}20`,
        boxShadow:       `0 0 0 3px ${cfg.hex}30`,
      }
    : isCompleted
    ? {
        borderColor:     `${cfg.hex}60`,
        backgroundColor: `${cfg.hex}12`,
      }
    : {};

  const iconColor = isActive
    ? cfg.hex
    : isCompleted
    ? `${cfg.hex}80`
    : undefined;

  return (
    <TooltipProvider delayDuration={150}>
      <Tooltip>
        <TooltipTrigger asChild>
          <button
            type="button"
            onClick={isClickable ? onClickNode : undefined}
            disabled={!isClickable}
            className={cn(
              "flex flex-col items-center gap-2.5 select-none outline-none group",
              isClickable ? "cursor-pointer" : "cursor-default"
            )}
          >
            <div
              className={cn(
                "relative w-11 h-11 rounded-full flex items-center justify-center border-2 transition-all duration-500 mb-2",
                isActive    && "scale-110 shadow-lg",
                !isActive && !isCompleted && "border-muted bg-muted/20",
                isClickable && !isActive && "group-hover:scale-105 group-hover:opacity-90"
              )}
              style={circleStyle}
            >
              <Icon
                size={17}
                className="transition-colors duration-300"
                style={{
                  color: iconColor ?? (isActive || isCompleted ? undefined : "hsl(var(--muted-foreground) / 0.3)"),
                }}
              />
              {isCompleted && (
                <span
                  className="absolute -top-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background"
                  style={{ backgroundColor: cfg.hex }}
                />
              )}
            </div>

            <span
              className={cn(
                "text-[11px] font-medium text-center leading-tight max-w-[76px] transition-colors duration-300",
                isActive    && "font-semibold",
                !isActive && !isCompleted && "text-muted-foreground/30"
              )}
              style={{
                color: isActive
                  ? cfg.hex
                  : isCompleted
                  ? "hsl(var(--muted-foreground) / 0.6)"
                  : undefined,
              }}
            >
              {stage.label}
            </span>
          </button>
        </TooltipTrigger>
        <TooltipContent side="bottom" className="text-xs max-w-[160px] text-center">
          {tooltipText}
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}

// ── Connector ─────────────────────────────────────────────────────────────────

interface ConnectorProps {
  isCompleted: boolean;
  cfg:         StatusConfig;
}

function Connector({ isCompleted, cfg }: ConnectorProps) {
  return (
    <div className="flex-1 flex items-center pb-7 mx-1 min-w-5">
      <div className="relative w-full h-[2px] rounded-full bg-muted/40 overflow-hidden">
        <div
          className="absolute inset-y-0 left-0 rounded-full transition-all duration-700 ease-in-out"
          style={{
            width:           isCompleted ? "100%" : "0%",
            backgroundColor: isCompleted ? cfg.hex : "transparent",
          }}
        />
      </div>
    </div>
  );
}

// ── Confirmation Dialog ───────────────────────────────────────────────────────

interface ConfirmDialogProps {
  open:          boolean;
  targetStatus:  RiskStatus | null;
  currentStatus: RiskStatus;
  cfg:           StatusConfig;
  onConfirm:     () => void;
  onCancel:      () => void;
}

function ConfirmDialog({
  open,
  targetStatus,
  currentStatus,
  cfg,
  onConfirm,
  onCancel,
}: ConfirmDialogProps) {
  if (!targetStatus) return null;

  const currentIndex = STAGE_IDS.indexOf(currentStatus);
  const targetIndex  = STAGE_IDS.indexOf(targetStatus);
  const isGoingBack  = targetIndex < currentIndex;
  const targetCfg    = STATUS_CONFIG[targetStatus];

  return (
    <AlertDialog open={open} onOpenChange={(v) => !v && onCancel()}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle className="flex items-center gap-2">
            {isGoingBack ? "Go back to" : "Proceed to"}{" "}
            <span
              className="font-bold"
              style={{ color: targetCfg.hex }}
            >
              {getLabel(targetStatus)}
            </span>
            ?
          </AlertDialogTitle>
          <AlertDialogDescription className="text-sm text-muted-foreground">
            {isGoingBack
              ? `This will move the risk status back from "${getLabel(currentStatus)}" to "${getLabel(targetStatus)}". Are you sure you want to recall this stage?`
              : `This will advance the risk status from "${getLabel(currentStatus)}" to "${getLabel(targetStatus)}". Do you want to proceed?`}
          </AlertDialogDescription>
        </AlertDialogHeader>

        {/* Stage transition visual */}
        <div className="flex items-center justify-center gap-3 py-2">
          <span
            className="text-xs font-semibold px-3 py-1 rounded-full border"
            style={{
              color:           cfg.hex,
              backgroundColor: `${cfg.hex}15`,
              borderColor:     `${cfg.hex}30`,
            }}
          >
            {getLabel(currentStatus)}
          </span>
          <span className="text-muted-foreground text-sm">
            {"→"}
          </span>
          <span
            className="text-xs font-semibold px-3 py-1 rounded-full border"
            style={{
              color:           targetCfg.hex,
              backgroundColor: `${targetCfg.hex}15`,
              borderColor:     `${targetCfg.hex}30`,
            }}
          >
            {getLabel(targetStatus)}
          </span>
        </div>

        <AlertDialogFooter>
          <AlertDialogCancel onClick={onCancel}>Cancel</AlertDialogCancel>
          <AlertDialogAction
            onClick={onConfirm}
            style={{ backgroundColor: targetCfg.hex, color: "#0d1117", border: "none" }}
          >
            {isGoingBack ? "Yes, Go Back" : "Yes, Proceed"}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}

// ── RiskWorkflow ──────────────────────────────────────────────────────────────

export default function RiskWorkflow({
  value,
  initialStatus = "identified",
  onChange,
  standalone,
}: RiskWorkflowProps) {
  const isControlled = value !== undefined;
  const [internalStatus, setInternalStatus] = useState<RiskStatus>(initialStatus);
  const currentStatus: RiskStatus = isControlled ? value! : internalStatus;

  // Confirmation dialog state
  const [pendingTarget, setPendingTarget] = useState<RiskStatus | null>(null);
  const [dialogOpen,    setDialogOpen]    = useState(false);

  const cfg         = STATUS_CONFIG[currentStatus] ?? STATUS_CONFIG["identified"];
  const activeIndex = STAGE_IDS.indexOf(currentStatus);
  const rules       = NAV_RULES[currentStatus] ?? { canProceed: [], canGoBack: [] };

  // Step 1: user clicks a stage → open confirmation dialog
  function requestNavigate(targetId: RiskStatus) {
    setPendingTarget(targetId);
    setDialogOpen(true);
  }

  // Step 2a: user confirms → actually navigate
  function confirmNavigate() {
    if (!pendingTarget) return;
    if (!isControlled) setInternalStatus(pendingTarget);
    onChange?.(pendingTarget);
    setDialogOpen(false);
    setPendingTarget(null);
  }

  // Step 2b: user cancels → dismiss
  function cancelNavigate() {
    setDialogOpen(false);
    setPendingTarget(null);
  }

  function getTooltip(stageId: RiskStatus, idx: number): string {
    if (stageId === currentStatus)           return "Current stage";
    if (rules.canProceed.includes(stageId)) return `Click to proceed → ${getLabel(stageId)}`;
    if (rules.canGoBack.includes(stageId))  return `Click to go back → ${getLabel(stageId)}`;
    if (idx < activeIndex)                  return "Completed";
    return "Not reachable from current stage";
  }

  function isClickable(stageId: RiskStatus): boolean {
    return rules.canProceed.includes(stageId) || rules.canGoBack.includes(stageId);
  }

  const card = (
    <>
      <Card
        className="w-full transition-all duration-500"
        style={{
          borderColor: `${cfg.hex}28`,
          boxShadow:   `0 0 0 1px ${cfg.hex}12, 0 8px 40px ${cfg.hex}12`,
        }}
      >
        <CardHeader className="pb-3 pt-5 px-6">
          <div className="flex items-center justify-between">
            <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-widest">
              Current Stage
            </CardTitle>
            <Badge
              variant="secondary"
              className="text-xs font-semibold px-2.5 py-0.5 rounded-full border"
              style={{
                color:           cfg.hex,
                backgroundColor: `${cfg.hex}15`,
                borderColor:     `${cfg.hex}30`,
              }}
            >
              {getLabel(currentStatus)}
            </Badge>
          </div>
        </CardHeader>

        <Separator />

        <CardContent className="px-6 pt-5 pb-6">
          <div className="flex items-start">
            {STAGES.map((stage, i) => {
              const isActive    = i === activeIndex;
              const isCompleted = i < activeIndex;
              return (
                <div key={stage.id} className="flex items-center flex-1 last:flex-none">
                  <StageNode
                    stage={stage}
                    isActive={isActive}
                    isCompleted={isCompleted}
                    cfg={cfg}
                    isClickable={isClickable(stage.id)}
                    onClickNode={() => requestNavigate(stage.id)}
                    tooltipText={getTooltip(stage.id, i)}
                  />
                  {i < STAGES.length - 1 && (
                    <Connector isCompleted={isCompleted} cfg={cfg} />
                  )}
                </div>
              );
            })}
          </div>

          {currentStatus === "closed" && (
            <div className="flex justify-center mt-4">
              <Badge
                className="text-xs px-3 py-1 rounded-full"
                style={{
                  backgroundColor: `${cfg.hex}20`,
                  color:           cfg.hex,
                  border:          `1px solid ${cfg.hex}30`,
                }}
              >
                ✓ Risk Closed
              </Badge>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Confirmation dialog — rendered outside Card so it's not clipped */}
      <ConfirmDialog
        open={dialogOpen}
        targetStatus={pendingTarget}
        currentStatus={currentStatus}
        cfg={cfg}
        onConfirm={confirmNavigate}
        onCancel={cancelNavigate}
      />
    </>
  );

  if (standalone) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-8">
        <div className="w-full max-w-[560px]">{card}</div>
      </div>
    );
  }

  return card;
}