import { useState } from "react";
import { ChevronLeft, Pencil, Check, X, GitBranch } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { StatusBadge } from "@/components/StatusBadge";
import { ProjectPicker } from "./ProjectPicker";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";

export interface InitiativeHeaderProps {
  initiative: {
    id: string;
    name: string;
    status: string;
    executionMode?: string;
    branch?: string | null;
    branchLocked?: boolean;
  };
  projects?: Array<{ id: string; name: string; url: string }>;
  onBack: () => void;
}

export function InitiativeHeader({
  initiative,
  projects,
  onBack,
}: InitiativeHeaderProps) {
  const [editingProjects, setEditingProjects] = useState(false);
  const [editIds, setEditIds] = useState<string[]>([]);
  const [editingBranch, setEditingBranch] = useState(false);
  const [branchValue, setBranchValue] = useState("");

  const utils = trpc.useUtils();

  const projectMutation = trpc.updateInitiativeProjects.useMutation({
    onSuccess: () => {
      setEditingProjects(false);
      utils.getInitiative.invalidate({ id: initiative.id });
      toast.success("Projects updated");
    },
    onError: (err) => {
      toast.error(err.message);
    },
  });

  const configMutation = trpc.updateInitiativeConfig.useMutation({
    onSuccess: () => {
      utils.getInitiative.invalidate({ id: initiative.id });
    },
    onError: (err) => {
      toast.error(err.message);
    },
  });

  function startEditingProjects() {
    setEditIds(projects?.map((p) => p.id) ?? []);
    setEditingProjects(true);
  }

  function saveProjects() {
    if (editIds.length === 0) {
      toast.error("At least one project is required");
      return;
    }
    projectMutation.mutate({
      initiativeId: initiative.id,
      projectIds: editIds,
    });
  }

  function toggleExecutionMode() {
    const newMode = initiative.executionMode === "yolo" ? "review_per_phase" : "yolo";
    configMutation.mutate({
      initiativeId: initiative.id,
      executionMode: newMode as "yolo" | "review_per_phase",
    });
  }

  function startEditingBranch() {
    setBranchValue(initiative.branch ?? "");
    setEditingBranch(true);
  }

  function saveBranch() {
    configMutation.mutate({
      initiativeId: initiative.id,
      branch: branchValue.trim() || null,
    });
    setEditingBranch(false);
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={onBack}>
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <h1 className="font-display text-xl font-semibold">{initiative.name}</h1>
          <StatusBadge status={initiative.status} />
          {initiative.executionMode && (
            <Badge
              variant="outline"
              className={`cursor-pointer select-none transition-colors ${
                initiative.executionMode === "yolo"
                  ? "border-status-warning-border text-status-warning-fg text-[10px] hover:bg-status-warning-bg"
                  : "border-status-active-border text-status-active-fg text-[10px] hover:bg-status-active-bg"
              }`}
              onClick={toggleExecutionMode}
            >
              {configMutation.isPending
                ? "..."
                : initiative.executionMode === "yolo"
                  ? "YOLO"
                  : "REVIEW"}
            </Badge>
          )}
          {!editingBranch && initiative.branch && (
            <Badge
              variant="outline"
              className={`gap-1 text-[10px] font-mono transition-colors ${
                initiative.branchLocked ? "" : "cursor-pointer hover:bg-muted"
              }`}
              onClick={initiative.branchLocked ? undefined : startEditingBranch}
            >
              <GitBranch className="h-3 w-3" />
              {initiative.branch}
            </Badge>
          )}
          {!editingBranch && !initiative.branch && !initiative.branchLocked && (
            <button
              className="text-[10px] text-muted-foreground hover:text-foreground transition-colors"
              onClick={startEditingBranch}
            >
              + branch
            </button>
          )}
          {editingBranch && (
            <div className="flex items-center gap-1">
              <GitBranch className="h-3 w-3 text-muted-foreground" />
              <Input
                value={branchValue}
                onChange={(e) => setBranchValue(e.target.value)}
                placeholder="cw/my-feature"
                className="h-6 w-40 text-xs font-mono"
                autoFocus
                onKeyDown={(e) => {
                  if (e.key === "Enter") saveBranch();
                  if (e.key === "Escape") setEditingBranch(false);
                }}
              />
              <Button variant="ghost" size="icon" className="h-5 w-5" onClick={saveBranch}>
                <Check className="h-3 w-3" />
              </Button>
              <Button variant="ghost" size="icon" className="h-5 w-5" onClick={() => setEditingBranch(false)}>
                <X className="h-3 w-3" />
              </Button>
            </div>
          )}
          {!editingProjects && projects && projects.length > 0 && (
            <>
              {projects.map((p) => (
                <Badge key={p.id} variant="outline" className="text-xs font-normal">
                  {p.name}
                </Badge>
              ))}
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={startEditingProjects}
              >
                <Pencil className="h-3 w-3" />
              </Button>
            </>
          )}
          {!editingProjects && (!projects || projects.length === 0) && (
            <Button
              variant="ghost"
              size="sm"
              className="text-xs text-muted-foreground"
              onClick={startEditingProjects}
            >
              + Add projects
            </Button>
          )}
        </div>
      </div>
      {editingProjects && (
        <div className="ml-11 max-w-sm space-y-2">
          <ProjectPicker value={editIds} onChange={setEditIds} />
          <div className="flex gap-2">
            <Button
              size="sm"
              onClick={saveProjects}
              disabled={editIds.length === 0 || projectMutation.isPending}
            >
              <Check className="mr-1 h-3 w-3" />
              {projectMutation.isPending ? "Saving..." : "Save"}
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => setEditingProjects(false)}
            >
              Cancel
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
