import { useEffect, useState } from "react";
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 {
  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 [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 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(),
        mergeRequiresApproval: true,
        branch: null,
        projects: [],
      };
      utils.listInitiatives.setData(undefined, (old = []) => [tempInitiative, ...old]);
      return { previousInitiatives };
    },
    onSuccess: () => {
      onOpenChange(false);
      toast.success("Initiative created");
    },
    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("");
      setBranch("");
      setProjectIds([]);
      setExecutionMode("review_per_phase");
      setError(null);
    }
  }, [open]);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    createMutation.mutate({
      name: name.trim(),
      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-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>
  );
}
