"use client";
import { useState, useMemo } from "react";
import {
  Plus,
  Edit3,
  Trash2,
  RefreshCw,
  Calendar,
  Clock,
  Sun,
  Moon,
  Users,
  Zap,
  ArrowLeftRight,
  Check,
  Loader2,
} from "lucide-react";
import { format, addDays, parseISO } from "date-fns";
import Modal from "./ui/Modal";
import Badge from "./ui/Badge";
import { cn } from "@/lib/utils";
import {
  SHIFT_PATTERNS,
  ROTATION_INTERVALS,
  getPattern,
  patternStats,
  getSquadSlot,
  suggestedOffsets,
  type Slot,
} from "@/lib/shiftPatterns";

interface SquadAssignment {
  orgNodeId: number;
  squadIndex: number;
  offsetDays: number;
  startsOnNights: boolean;
}

interface RotationConfig {
  id: number;
  name: string;
  patternKey: string;
  rotationDays: number;
  shiftHours: number;
  startDate: string;
  dayNightRotation: boolean;
  dayNightIntervalDays: number;
  dayShiftTemplateId: number | null;
  nightShiftTemplateId: number | null;
  generatedThrough: string | null;
  isActive: boolean | null;
  orgNodeId: number | null;
  pattern: unknown;
  squads?: SquadAssignment[];
}

interface OrgNode {
  id: number;
  name: string;
  type: string;
  color: string | null;
  parentId: number | null;
}

interface ShiftTemplate {
  id: number;
  name: string;
  type: string;
  startTime: string;
  endTime: string;
  color: string | null;
}

interface Props {
  rotations: RotationConfig[];
  orgNodes: OrgNode[];
  shiftTemplates: ShiftTemplate[];
  employees: Array<{ id: number; orgNodeId: number | null; isActive: boolean | null }>;
  departmentId: number;
  onUpdate: () => void;
  onScheduleChanged: () => void;
}

const SLOT_STYLES: Record<string, { bg: string; label: string; text: string }> = {
  DAY: { bg: "#3B82F6", label: "D", text: "#fff" },
  NIGHT: { bg: "#6D28D9", label: "N", text: "#fff" },
  OFF: { bg: "#E2E8F0", label: "·", text: "#94A3B8" },
};

export default function RotationManager({
  rotations,
  orgNodes,
  shiftTemplates,
  employees,
  departmentId,
  onUpdate,
  onScheduleChanged,
}: Props) {
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<RotationConfig | null>(null);
  const [saving, setSaving] = useState(false);
  const [generatingId, setGeneratingId] = useState<number | null>(null);
  const [toast, setToast] = useState<string | null>(null);

  const squadNodes = useMemo(
    () => orgNodes.filter((n) => n.type === "squad" || n.type === "unit" || n.type === "district"),
    [orgNodes]
  );

  const dayTemplates = shiftTemplates.filter((t) => t.type !== "night");
  const nightTemplates = shiftTemplates.filter((t) => t.type === "night");

  interface FormState {
    name: string;
    patternKey: string;
    startDate: string;
    dayNightRotation: boolean;
    dayNightIntervalDays: number;
    dayShiftTemplateId: number | null;
    nightShiftTemplateId: number | null;
    isActive: boolean;
    customSlots: Slot[];
    squads: SquadAssignment[];
  }

  const defaultForm = (): FormState => {
    const def = SHIFT_PATTERNS[0];
    return {
      name: "",
      patternKey: def.key,
      startDate: format(new Date(), "yyyy-MM-dd"),
      dayNightRotation: def.defaultRotationIntervalDays > 0,
      dayNightIntervalDays: def.defaultRotationIntervalDays || 28,
      dayShiftTemplateId: (dayTemplates[0] ?? shiftTemplates[0])?.id ?? null,
      nightShiftTemplateId: (nightTemplates[0] ?? shiftTemplates[shiftTemplates.length - 1])?.id ?? null,
      isActive: true,
      customSlots: def.slots as Slot[],
      squads: [] as SquadAssignment[],
    };
  };

  const [form, setForm] = useState(defaultForm());

  const activeDef = getPattern(form.patternKey);
  const activeSlots: Slot[] = form.patternKey === "custom" ? form.customSlots : activeDef.slots;
  const stats = patternStats(activeSlots, activeDef.shiftHours);

  const openAdd = () => {
    setEditing(null);
    setForm(defaultForm());
    setShowModal(true);
  };

  const openEdit = (rot: RotationConfig) => {
    setEditing(rot);
    const custom = (rot.pattern as { slots?: Slot[] } | null)?.slots;
    setForm({
      name: rot.name,
      patternKey: rot.patternKey ?? "pitman",
      startDate: rot.startDate,
      dayNightRotation: rot.dayNightRotation,
      dayNightIntervalDays: rot.dayNightIntervalDays || 28,
      dayShiftTemplateId: rot.dayShiftTemplateId,
      nightShiftTemplateId: rot.nightShiftTemplateId,
      isActive: rot.isActive ?? true,
      customSlots: custom && custom.length ? custom : getPattern(rot.patternKey).slots,
      squads: rot.squads ?? [],
    });
    setShowModal(true);
  };

  const selectPattern = (key: string) => {
    const def = getPattern(key);
    setForm((prev) => {
      const offsets = suggestedOffsets(def.slots.length, Math.max(prev.squads.length, 1));
      return {
        ...prev,
        patternKey: key,
        customSlots: def.slots,
        dayNightRotation: def.fixedDayNight ? false : def.defaultRotationIntervalDays > 0,
        dayNightIntervalDays: def.defaultRotationIntervalDays || prev.dayNightIntervalDays || 28,
        squads: prev.squads.map((s, i) => ({ ...s, offsetDays: offsets[i] ?? 0 })),
      };
    });
  };

  const toggleSquad = (nodeId: number) => {
    setForm((prev) => {
      const exists = prev.squads.some((s) => s.orgNodeId === nodeId);
      const next = exists
        ? prev.squads.filter((s) => s.orgNodeId !== nodeId)
        : [
            ...prev.squads,
            { orgNodeId: nodeId, squadIndex: prev.squads.length, offsetDays: 0, startsOnNights: false },
          ];
      const cycle = (prev.patternKey === "custom" ? prev.customSlots : getPattern(prev.patternKey).slots).length;
      const offsets = suggestedOffsets(cycle, next.length);
      return {
        ...prev,
        squads: next.map((s, i) => ({
          ...s,
          squadIndex: i,
          offsetDays: s.offsetDays || offsets[i] || 0,
          startsOnNights: exists ? s.startsOnNights : i % 2 === 1,
        })),
      };
    });
  };

  const autoBalance = () => {
    setForm((prev) => {
      const cycle = (prev.patternKey === "custom" ? prev.customSlots : getPattern(prev.patternKey).slots).length;
      const offsets = suggestedOffsets(cycle, prev.squads.length);
      return {
        ...prev,
        squads: prev.squads.map((s, i) => ({
          ...s,
          squadIndex: i,
          offsetDays: offsets[i] ?? 0,
          startsOnNights: i % 2 === 1,
        })),
      };
    });
  };

  const updateSquad = (nodeId: number, patch: Partial<SquadAssignment>) => {
    setForm((prev) => ({
      ...prev,
      squads: prev.squads.map((s) => (s.orgNodeId === nodeId ? { ...s, ...patch } : s)),
    }));
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const payload = {
        departmentId,
        name: form.name,
        patternKey: form.patternKey,
        rotationDays: activeSlots.length,
        shiftHours: activeDef.shiftHours,
        startDate: form.startDate,
        dayNightRotation: form.dayNightRotation,
        dayNightIntervalDays: form.dayNightIntervalDays,
        dayShiftTemplateId: form.dayShiftTemplateId,
        nightShiftTemplateId: form.nightShiftTemplateId,
        isActive: form.isActive,
        orgNodeId: form.squads[0]?.orgNodeId ?? null,
        pattern: form.patternKey === "custom" ? { slots: form.customSlots } : null,
        squads: form.squads,
      };
      await fetch("/api/rotation-configs", {
        method: editing ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editing ? { ...payload, id: editing.id } : payload),
      });
      setShowModal(false);
      onUpdate();
      setToast(editing ? "Rotation updated" : "Rotation created");
      setTimeout(() => setToast(null), 2500);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this rotation and the shifts it generated?")) return;
    await fetch(`/api/rotation-configs?id=${id}`, { method: "DELETE" });
    onUpdate();
    onScheduleChanged();
  };

  const handleGenerateYear = async (rot: RotationConfig) => {
    setGeneratingId(rot.id);
    try {
      const start = format(new Date(), "yyyy-MM-dd");
      const end = format(addDays(new Date(), 364), "yyyy-MM-dd");
      const res = await fetch("/api/schedules/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ departmentId, rotationConfigId: rot.id, startDate: start, endDate: end, clearExisting: true }),
      });
      const data = await res.json();
      if (data.success) {
        setToast(`Generated ${data.generated.toLocaleString()} shifts for ${rot.name}`);
        onUpdate();
        onScheduleChanged();
      } else {
        setToast(data.error ?? "Generation failed");
      }
      setTimeout(() => setToast(null), 4000);
    } finally {
      setGeneratingId(null);
    }
  };

  const squadCount = (nodeId: number) =>
    employees.filter((e) => e.orgNodeId === nodeId && e.isActive !== false).length;

  return (
    <div>
      {toast && (
        <div className="mb-4 flex items-center gap-2 bg-green-50 border border-green-200 text-green-700 rounded-xl px-4 py-2.5 text-sm">
          <Check size={16} /> {toast}
        </div>
      )}

      <div className="flex flex-wrap justify-between items-center gap-3 mb-5">
        <p className="text-sm text-slate-500">
          Pick a recognised plan (Pitman, Kelly, Panama, DuPont…), assign squads, and set how often they swap days/nights.
        </p>
        <button
          onClick={openAdd}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-medium hover:bg-blue-700"
        >
          <Plus size={16} />
          New Rotation
        </button>
      </div>

      <div className="space-y-4">
        {rotations.length === 0 && (
          <div className="text-center py-14 text-slate-400 border-2 border-dashed border-slate-200 rounded-2xl">
            <RefreshCw size={38} className="mx-auto mb-3 opacity-30" />
            <p className="font-medium">No rotations configured</p>
            <p className="text-sm">Create one to unlock auto-scheduling</p>
          </div>
        )}

        {rotations.map((rot) => {
          const def = getPattern(rot.patternKey);
          const slots: Slot[] =
            rot.patternKey === "custom"
              ? ((rot.pattern as { slots?: Slot[] } | null)?.slots ?? def.slots)
              : def.slots;
          const s = patternStats(slots, rot.shiftHours ?? def.shiftHours);
          const squads = rot.squads ?? [];

          return (
            <div key={rot.id} className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
              <div className="p-5">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div className="flex-1 min-w-[240px]">
                    <div className="flex items-center gap-2 flex-wrap mb-2">
                      <h3 className="font-bold text-slate-800 text-lg">{rot.name}</h3>
                      <Badge color="#2563EB" variant="solid">{def.shortName}</Badge>
                      <Badge color={rot.isActive ? "#10B981" : "#94A3B8"}>
                        {rot.isActive ? "Active" : "Inactive"}
                      </Badge>
                      {rot.dayNightRotation && (
                        <Badge color="#7C3AED">
                          <ArrowLeftRight size={10} className="inline mr-1" />
                          Swaps every {rot.dayNightIntervalDays}d
                        </Badge>
                      )}
                    </div>
                    <p className="text-sm text-slate-500 mb-3">{def.description}</p>
                    <div className="flex flex-wrap items-center gap-x-5 gap-y-1 text-sm text-slate-500">
                      <span className="flex items-center gap-1.5">
                        <RefreshCw size={14} /> {s.cycleDays}-day cycle
                      </span>
                      <span className="flex items-center gap-1.5">
                        <Clock size={14} /> {rot.shiftHours ?? def.shiftHours}h shifts • ~{s.avgHoursPerWeek}h/wk
                      </span>
                      <span className="flex items-center gap-1.5">
                        <Calendar size={14} /> Anchor {rot.startDate}
                      </span>
                      <span className="flex items-center gap-1.5">
                        <Users size={14} /> {squads.length} squad{squads.length !== 1 ? "s" : ""}
                      </span>
                      {rot.generatedThrough && (
                        <span className="flex items-center gap-1.5 text-green-600">
                          <Check size={14} /> Built through {rot.generatedThrough}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => handleGenerateYear(rot)}
                      disabled={generatingId === rot.id}
                      className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-blue-600 text-white text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
                    >
                      {generatingId === rot.id ? (
                        <Loader2 size={14} className="animate-spin" />
                      ) : (
                        <Zap size={14} />
                      )}
                      Build Year
                    </button>
                    <button onClick={() => openEdit(rot)} className="p-2 rounded-xl bg-slate-50 text-slate-500 hover:bg-slate-100">
                      <Edit3 size={16} />
                    </button>
                    <button onClick={() => handleDelete(rot.id)} className="p-2 rounded-xl bg-red-50 text-red-400 hover:bg-red-100">
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>

                {/* Per-squad timeline preview */}
                {squads.length > 0 && (
                  <div className="mt-5 border-t border-slate-100 pt-4">
                    <p className="text-xs text-slate-400 mb-2 font-semibold uppercase tracking-wide">
                      Next 28 days by squad
                    </p>
                    <div className="space-y-1.5 overflow-x-auto">
                      {squads.map((sq) => {
                        const node = orgNodes.find((n) => n.id === sq.orgNodeId);
                        const anchorIndex = Math.max(
                          0,
                          Math.round(
                            (new Date().getTime() - parseISO(rot.startDate).getTime()) / 86400000
                          )
                        );
                        return (
                          <div key={sq.orgNodeId} className="flex items-center gap-2 min-w-max">
                            <div className="w-36 flex-shrink-0 flex items-center gap-1.5">
                              <span
                                className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                                style={{ backgroundColor: node?.color ?? "#3B82F6" }}
                              />
                              <span className="text-xs font-medium text-slate-700 truncate">
                                {node?.name ?? `Unit ${sq.orgNodeId}`}
                              </span>
                              <span className="text-[10px] text-slate-400">({squadCount(sq.orgNodeId)})</span>
                            </div>
                            <div className="flex gap-0.5">
                              {Array.from({ length: 28 }, (_, d) => {
                                const resolved = getSquadSlot({
                                  slots,
                                  dayIndex: anchorIndex + d,
                                  squadOffsetDays: sq.offsetDays,
                                  dayNightRotation: rot.dayNightRotation,
                                  dayNightIntervalDays: rot.dayNightIntervalDays,
                                  startsOnNights: sq.startsOnNights,
                                });
                                const style = SLOT_STYLES[resolved];
                                return (
                                  <div
                                    key={d}
                                    className="w-5 h-5 rounded flex items-center justify-center text-[10px] font-bold"
                                    style={{ backgroundColor: style.bg, color: style.text }}
                                    title={`${format(addDays(new Date(), d), "EEE MMM d")} — ${resolved}`}
                                  >
                                    {style.label}
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                    <div className="flex gap-4 mt-3 text-xs text-slate-500">
                      <span className="flex items-center gap-1.5">
                        <span className="w-3 h-3 rounded" style={{ background: "#3B82F6" }} /> Day
                      </span>
                      <span className="flex items-center gap-1.5">
                        <span className="w-3 h-3 rounded" style={{ background: "#6D28D9" }} /> Night
                      </span>
                      <span className="flex items-center gap-1.5">
                        <span className="w-3 h-3 rounded bg-slate-200" /> Off
                      </span>
                    </div>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* ---------------------------------------------------------- editor */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title={editing ? "Edit Rotation" : "New Rotation"}
        size="xl"
      >
        <div className="space-y-6">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Rotation Name *</label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              placeholder="e.g., Patrol Division — Pitman"
              className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Pattern picker */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">Scheduling Plan</label>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-64 overflow-y-auto pr-1">
              {SHIFT_PATTERNS.map((p) => {
                const ps = patternStats(p.slots, p.shiftHours);
                const selected = form.patternKey === p.key;
                return (
                  <button
                    key={p.key}
                    onClick={() => selectPattern(p.key)}
                    className={cn(
                      "text-left p-3 rounded-xl border-2 transition-all",
                      selected ? "border-blue-500 bg-blue-50" : "border-slate-200 hover:border-slate-300"
                    )}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className={cn("text-sm font-bold", selected ? "text-blue-700" : "text-slate-800")}>
                        {p.name}
                      </span>
                      <Badge color={selected ? "#2563EB" : "#94A3B8"}>{p.category}</Badge>
                    </div>
                    <p className="text-xs text-slate-500 line-clamp-2 mb-2">{p.description}</p>
                    <div className="flex gap-3 text-[11px] text-slate-500 font-medium">
                      <span>{ps.cycleDays}d cycle</span>
                      <span>{p.shiftHours}h shifts</span>
                      <span>~{ps.avgHoursPerWeek}h/wk</span>
                      <span>{p.recommendedTeams} teams</span>
                    </div>
                    <div className="flex gap-0.5 mt-2 flex-wrap">
                      {p.slots.slice(0, 28).map((slot, i) => (
                        <span
                          key={i}
                          className="w-3.5 h-3.5 rounded-sm"
                          style={{
                            backgroundColor:
                              slot === "O" ? "#E2E8F0" : slot === "N" ? "#6D28D9" : slot === "D" ? "#3B82F6" : "#0EA5E9",
                          }}
                        />
                      ))}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Custom pattern editor */}
          {form.patternKey === "custom" && (
            <div className="border border-slate-200 rounded-xl p-4">
              <div className="flex items-center justify-between mb-3">
                <label className="text-sm font-medium text-slate-700">Custom Cycle ({form.customSlots.length} days)</label>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() =>
                      setForm({ ...form, customSlots: [...form.customSlots, "O"] as Slot[] })
                    }
                    className="px-2.5 py-1 text-xs rounded-lg bg-slate-100 hover:bg-slate-200"
                  >
                    + Day
                  </button>
                  <button
                    onClick={() => setForm({ ...form, customSlots: form.customSlots.slice(0, -1) })}
                    disabled={form.customSlots.length <= 1}
                    className="px-2.5 py-1 text-xs rounded-lg bg-slate-100 hover:bg-slate-200 disabled:opacity-40"
                  >
                    − Day
                  </button>
                </div>
              </div>
              <div className="flex flex-wrap gap-1.5">
                {form.customSlots.map((slot, i) => (
                  <button
                    key={i}
                    onClick={() => {
                      const cycle: Slot[] = ["W", "D", "N", "O"];
                      const next = cycle[(cycle.indexOf(slot) + 1) % cycle.length];
                      const copy = [...form.customSlots];
                      copy[i] = next;
                      setForm({ ...form, customSlots: copy });
                    }}
                    className="w-10 rounded-lg py-1.5 text-[11px] font-bold text-white transition-transform hover:scale-105"
                    style={{
                      backgroundColor:
                        slot === "O" ? "#CBD5E1" : slot === "N" ? "#6D28D9" : slot === "D" ? "#3B82F6" : "#0EA5E9",
                    }}
                    title="Click to cycle: Work → Day → Night → Off"
                  >
                    {slot === "O" ? "OFF" : slot}
                  </button>
                ))}
              </div>
              <p className="text-xs text-slate-400 mt-2">
                W = work (day/night set by squad rotation) · D = forced day · N = forced night · OFF = rest day
              </p>
            </div>
          )}

          {/* Summary */}
          <div className="grid grid-cols-4 gap-3">
            {[
              { label: "Cycle", value: `${stats.cycleDays} days` },
              { label: "Work days", value: `${stats.onDays}` },
              { label: "Days off", value: `${stats.offDays}` },
              { label: "Avg / week", value: `${stats.avgHoursPerWeek}h` },
            ].map((m) => (
              <div key={m.label} className="bg-slate-50 rounded-xl p-3 text-center">
                <div className="text-lg font-bold text-slate-800">{m.value}</div>
                <div className="text-[11px] text-slate-500">{m.label}</div>
              </div>
            ))}
          </div>

          {/* Day/night rotation */}
          <div className="border border-slate-200 rounded-xl p-4 space-y-3">
            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                checked={form.dayNightRotation}
                onChange={(e) => setForm({ ...form, dayNightRotation: e.target.checked })}
                className="w-4 h-4 rounded border-slate-300 text-blue-600"
              />
              <span className="text-sm font-medium text-slate-700 flex items-center gap-2">
                <ArrowLeftRight size={15} className="text-purple-500" />
                Squads rotate between days and nights
              </span>
            </label>
            {form.dayNightRotation && (
              <div className="pl-7">
                <label className="block text-xs font-medium text-slate-600 mb-1">Swap interval</label>
                <div className="flex flex-wrap gap-2">
                  {ROTATION_INTERVALS.filter((i) => i.value > 0).map((i) => (
                    <button
                      key={i.value}
                      onClick={() => setForm({ ...form, dayNightIntervalDays: i.value })}
                      className={cn(
                        "px-3 py-1.5 rounded-xl text-xs font-medium transition-colors",
                        form.dayNightIntervalDays === i.value
                          ? "bg-purple-600 text-white"
                          : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                      )}
                    >
                      {i.label}
                    </button>
                  ))}
                </div>
                <div className="flex items-center gap-2 mt-2">
                  <input
                    type="number"
                    min={1}
                    max={365}
                    value={form.dayNightIntervalDays}
                    onChange={(e) =>
                      setForm({ ...form, dayNightIntervalDays: Math.max(1, parseInt(e.target.value) || 1) })
                    }
                    className="w-24 border border-slate-300 rounded-xl px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  <span className="text-xs text-slate-500">custom interval in days</span>
                </div>
              </div>
            )}
          </div>

          {/* Squad assignment */}
          <div className="border border-slate-200 rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <label className="text-sm font-medium text-slate-700">
                Squads on this rotation ({form.squads.length})
              </label>
              <button
                onClick={autoBalance}
                disabled={form.squads.length === 0}
                className="text-xs px-3 py-1.5 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 font-medium disabled:opacity-40"
              >
                Auto-balance phases
              </button>
            </div>

            <div className="flex flex-wrap gap-2 mb-4">
              {squadNodes.map((n) => {
                const selected = form.squads.some((s) => s.orgNodeId === n.id);
                return (
                  <button
                    key={n.id}
                    onClick={() => toggleSquad(n.id)}
                    className={cn(
                      "flex items-center gap-2 px-3 py-1.5 rounded-xl border-2 text-xs font-medium transition-all",
                      selected ? "border-blue-500 bg-blue-50 text-blue-700" : "border-slate-200 text-slate-600"
                    )}
                  >
                    <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: n.color ?? "#3B82F6" }} />
                    {n.name}
                    <span className="text-slate-400">({squadCount(n.id)})</span>
                  </button>
                );
              })}
              {squadNodes.length === 0 && (
                <p className="text-xs text-slate-400 italic">Create squads on the Org Chart tab first.</p>
              )}
            </div>

            {form.squads.length > 0 && (
              <div className="space-y-2">
                {form.squads.map((sq) => {
                  const node = orgNodes.find((n) => n.id === sq.orgNodeId);
                  return (
                    <div key={sq.orgNodeId} className="flex flex-wrap items-center gap-3 bg-slate-50 rounded-xl p-3">
                      <span className="text-sm font-medium text-slate-700 min-w-[130px] flex items-center gap-1.5">
                        <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: node?.color ?? "#3B82F6" }} />
                        {node?.name}
                      </span>
                      <div className="flex items-center gap-2">
                        <label className="text-xs text-slate-500">Cycle offset</label>
                        <input
                          type="number"
                          min={0}
                          max={activeSlots.length - 1}
                          value={sq.offsetDays}
                          onChange={(e) =>
                            updateSquad(sq.orgNodeId, { offsetDays: Math.max(0, parseInt(e.target.value) || 0) })
                          }
                          className="w-16 border border-slate-300 rounded-lg px-2 py-1 text-xs"
                        />
                        <span className="text-xs text-slate-400">days</span>
                      </div>
                      <div className="flex rounded-lg overflow-hidden border border-slate-300">
                        <button
                          onClick={() => updateSquad(sq.orgNodeId, { startsOnNights: false })}
                          className={cn(
                            "flex items-center gap-1 px-2.5 py-1 text-xs font-medium",
                            !sq.startsOnNights ? "bg-blue-600 text-white" : "bg-white text-slate-500"
                          )}
                        >
                          <Sun size={12} /> Starts Days
                        </button>
                        <button
                          onClick={() => updateSquad(sq.orgNodeId, { startsOnNights: true })}
                          className={cn(
                            "flex items-center gap-1 px-2.5 py-1 text-xs font-medium",
                            sq.startsOnNights ? "bg-purple-700 text-white" : "bg-white text-slate-500"
                          )}
                        >
                          <Moon size={12} /> Starts Nights
                        </button>
                      </div>
                      {/* mini preview */}
                      <div className="flex gap-0.5 ml-auto">
                        {Array.from({ length: 14 }, (_, d) => {
                          const resolved = getSquadSlot({
                            slots: activeSlots,
                            dayIndex: d,
                            squadOffsetDays: sq.offsetDays,
                            dayNightRotation: form.dayNightRotation,
                            dayNightIntervalDays: form.dayNightIntervalDays,
                            startsOnNights: sq.startsOnNights,
                          });
                          const st = SLOT_STYLES[resolved];
                          return (
                            <span
                              key={d}
                              className="w-4 h-4 rounded-sm text-[9px] font-bold flex items-center justify-center"
                              style={{ backgroundColor: st.bg, color: st.text }}
                            >
                              {st.label}
                            </span>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Templates + anchor */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1 flex items-center gap-1.5">
                <Sun size={14} className="text-blue-500" /> Day shift
              </label>
              <select
                value={form.dayShiftTemplateId ?? ""}
                onChange={(e) =>
                  setForm({ ...form, dayShiftTemplateId: e.target.value ? parseInt(e.target.value) : null })
                }
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {shiftTemplates.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.name} ({t.startTime}–{t.endTime})
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1 flex items-center gap-1.5">
                <Moon size={14} className="text-purple-500" /> Night shift
              </label>
              <select
                value={form.nightShiftTemplateId ?? ""}
                onChange={(e) =>
                  setForm({ ...form, nightShiftTemplateId: e.target.value ? parseInt(e.target.value) : null })
                }
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {shiftTemplates.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.name} ({t.startTime}–{t.endTime})
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Cycle anchor date</label>
              <input
                type="date"
                value={form.startDate}
                onChange={(e) => setForm({ ...form, startDate: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div className="flex gap-3 pt-1">
            <button
              onClick={handleSave}
              disabled={saving || !form.name || form.squads.length === 0}
              className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 disabled:opacity-50"
            >
              {saving ? "Saving…" : editing ? "Save Rotation" : "Create Rotation"}
            </button>
            <button
              onClick={() => setShowModal(false)}
              className="px-4 py-2.5 border border-slate-200 rounded-xl text-slate-600 hover:bg-slate-50"
            >
              Cancel
            </button>
          </div>
          {form.squads.length === 0 && (
            <p className="text-xs text-amber-600 -mt-3">Select at least one squad to save this rotation.</p>
          )}
        </div>
      </Modal>
    </div>
  );
}
