"use client";

import React, { useState } from "react";
import {
  Play,
  PauseCircle,
  CheckCircle,
  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 IssueStatus = "Active" | "On hold" | "Resolved";

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

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

interface StatusConfig {
  hex: string;
}

interface IssueWorkflowProps {
  value?: IssueStatus;                     // controlled
  initialStatus?: IssueStatus;             // uncontrolled
  onChange?: (status: IssueStatus) => void;
  standalone?: boolean;
}

/* ───────────────── Data ───────────────── */

const STAGES: Stage[] = [
  { id: "Active", label: "Active", icon: Play },
{ id: "On hold", label: "On Hold", icon: PauseCircle },
{ id: "Resolved", label: "Resolved", icon: CheckCircle }
];

const NAV_RULES: Record<IssueStatus, NavRule> = {
  "Active": {
    canProceed: ["On hold", "Resolved"],
    canGoBack: [],
  },
  "On hold": {
    canProceed: ["Active", "Resolved"],
    canGoBack: ["Active"],
  },
  "Resolved": {
    canProceed: [],
    canGoBack: ["Active", "On hold"],
  },
};

const STATUS_CONFIG: Record<IssueStatus, StatusConfig> = {
  "Active": { hex: "#3b82f6" },
  "On hold": { hex: "#f59e0b" },
  "Resolved": { hex: "#22c55e" },
};

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

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

/* ───────────────── Stage Node ───────────────── */

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={18}
                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 ───────────────── */

function Connector({ isCompleted, cfg }: { isCompleted: boolean; cfg: StatusConfig }) {
  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 ───────────────── */

function ConfirmDialog({
  open,
  targetStatus,
  currentStatus,
  onConfirm,
  onCancel,
}: {
  open: boolean;
  targetStatus: IssueStatus | null;
  currentStatus: IssueStatus;
  onConfirm: () => void;
  onCancel: () => void;
}) {
  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];
  const currentCfg = STATUS_CONFIG[currentStatus];

  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 issue status back from "${getLabel(
                currentStatus
              )}" to "${getLabel(targetStatus)}".`
              : `This will advance the issue status from "${getLabel(
                currentStatus
              )}" to "${getLabel(targetStatus)}".`}
          </AlertDialogDescription>
        </AlertDialogHeader>

        <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: currentCfg.hex,
              backgroundColor: `${currentCfg.hex}15`,
              borderColor: `${currentCfg.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>
  );
}

/* ───────────────── IssueWorkflow Component ───────────────── */

export default function IssueWorkflow({
  value,
 initialStatus = "Active",
  onChange,
  standalone,
}: IssueWorkflowProps) {
  const isControlled = value !== undefined;
  const [internalStatus, setInternalStatus] = useState<IssueStatus>(initialStatus);

  const currentStatus: IssueStatus = isControlled ? value! : internalStatus;

  const [pendingTarget, setPendingTarget] = useState<IssueStatus | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);

  const cfg = STATUS_CONFIG[currentStatus];
  const activeIndex = STAGE_IDS.indexOf(currentStatus);
  const rules = NAV_RULES[currentStatus];

  function requestNavigate(targetId: IssueStatus) {
    setPendingTarget(targetId);
    setDialogOpen(true);
  }

  function confirmNavigate() {
    if (!pendingTarget) return;
    if (!isControlled) setInternalStatus(pendingTarget);
    onChange?.(pendingTarget);
    setDialogOpen(false);
    setPendingTarget(null);
  }

  function cancelNavigate() {
    setDialogOpen(false);
    setPendingTarget(null);
  }

  function getTooltip(stageId: IssueStatus, 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: IssueStatus): 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">
              Issue Status
            </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 === "Resolved" && (
            <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`,
                }}
              >
                ✓ Issue Resolved
              </Badge>
            </div>
          )}
        </CardContent>
      </Card>

      <ConfirmDialog
        open={dialogOpen}
        targetStatus={pendingTarget}
        currentStatus={currentStatus}
        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;
}