import { useEffect, useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toast } from "sonner";
import { trpc } from "@/lib/trpc";
import { ProjectPicker } from "./ProjectPicker";

interface CreateInitiativeDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CreateInitiativeDialog({
  open,
  onOpenChange,
}: CreateInitiativeDialogProps) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [branch, setBranch] = useState("");
  const [projectIds, setProjectIds] = useState<string[]>([]);
  const [executionMode, setExecutionMode] = useState<"yolo" | "review_per_phase">("review_per_phase");
  const [error, setError] = useState<string | null>(null);

  const navigate = useNavigate();
  const utils = trpc.useUtils();

  const createMutation = trpc.createInitiative.useMutation({
    onMutate: async ({ name }) => {
      await utils.listInitiatives.cancel();
      const previousInitiatives = utils.listInitiatives.getData();
      const tempInitiative = {
        id: `temp-${Date.now()}`,
        name: name.trim(),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        branch: null,
        projects: [],
        activity: { state: 'idle' as const, phasesTotal: 0, phasesCompleted: 0 },
      };
      utils.listInitiatives.setData(undefined, (old = []) => [tempInitiative, ...old]);
      return { previousInitiatives };
    },
    onSuccess: (data) => {
      onOpenChange(false);
      toast.success("Initiative created");
      navigate({ to: "/initiatives/$id", params: { id: data.id } });
    },
    onError: (err, _variables, context) => {
      if (context?.previousInitiatives) {
        utils.listInitiatives.setData(undefined, context.previousInitiatives);
      }
      setError(err.message);
      toast.error("Failed to create initiative");
    },
  });

  // Reset form when dialog opens
  useEffect(() => {
    if (open) {
      setName("");
      setDescription("");
      setBranch("");
      setProjectIds([]);
      setExecutionMode("review_per_phase");
      setError(null);
    }
  }, [open]);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    createMutation.mutate({
      name: name.trim(),
      description: description.trim() || undefined,
      branch: branch.trim() || null,
      projectIds: projectIds.length > 0 ? projectIds : undefined,
      executionMode,
    });
  }

  const canSubmit = name.trim().length > 0 && !createMutation.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create Initiative</DialogTitle>
          <DialogDescription>
            Create a new initiative to plan and execute work.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="initiative-name">Name</Label>
            <Input
              id="initiative-name"
              placeholder="e.g. User Authentication"
              value={name}
              onChange={(e) => setName(e.target.value)}
              autoFocus
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="initiative-description">
              Description{" "}
              <span className="text-muted-foreground font-normal">
                (optional — seeds root page and spawns refine agent)
              </span>
            </Label>
            <Textarea
              id="initiative-description"
              placeholder="Describe what needs to be done..."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="initiative-branch">
              Branch{" "}
              <span className="text-muted-foreground font-normal">
                (optional — auto-generated if blank)
              </span>
            </Label>
            <Input
              id="initiative-branch"
              placeholder="e.g. cw/my-feature"
              value={branch}
              onChange={(e) => setBranch(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label>Execution Mode</Label>
            <Select value={executionMode} onValueChange={(v) => setExecutionMode(v as "yolo" | "review_per_phase")}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="review_per_phase">Review per Phase</SelectItem>
                <SelectItem value="yolo">YOLO (auto-merge)</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>
              Projects{" "}
              <span className="text-muted-foreground font-normal">
                (optional)
              </span>
            </Label>
            <ProjectPicker value={projectIds} onChange={setProjectIds} />
          </div>
          {error && (
            <p className="text-sm text-destructive">{error}</p>
          )}
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={!canSubmit}>
              {createMutation.isPending ? "Creating..." : "Create"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
