import { useState } from "react";
import { ChevronLeft, Pencil, Check, GitBranch } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
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;
  };
  projects?: Array<{ id: string; name: string; url: string }>;
  onBack: () => void;
}

export function InitiativeHeader({
  initiative,
  projects,
  onBack,
}: InitiativeHeaderProps) {
  const [editing, setEditing] = useState(false);
  const [editIds, setEditIds] = useState<string[]>([]);

  const updateMutation = trpc.updateInitiativeProjects.useMutation({
    onSuccess: () => {
      setEditing(false);
      toast.success("Projects updated");
    },
    onError: (err) => {
      toast.error(err.message);
    },
  });

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

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

  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="text-xl font-semibold">{initiative.name}</h1>
          <StatusBadge status={initiative.status} />
          {initiative.executionMode && (
            <Badge
              variant="outline"
              className={
                initiative.executionMode === "yolo"
                  ? "border-orange-300 text-orange-700 text-[10px]"
                  : "border-blue-300 text-blue-700 text-[10px]"
              }
            >
              {initiative.executionMode === "yolo" ? "YOLO" : "REVIEW"}
            </Badge>
          )}
          {initiative.branch && (
            <Badge variant="outline" className="gap-1 text-[10px] font-mono">
              <GitBranch className="h-3 w-3" />
              {initiative.branch}
            </Badge>
          )}
          {!editing && 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={startEditing}
              >
                <Pencil className="h-3 w-3" />
              </Button>
            </>
          )}
          {!editing && (!projects || projects.length === 0) && (
            <Button
              variant="ghost"
              size="sm"
              className="text-xs text-muted-foreground"
              onClick={startEditing}
            >
              + Add projects
            </Button>
          )}
        </div>
      </div>
      {editing && (
        <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 || updateMutation.isPending}
            >
              <Check className="mr-1 h-3 w-3" />
              {updateMutation.isPending ? "Saving..." : "Save"}
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => setEditing(false)}
            >
              Cancel
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
