"use client";

import * as React from "react";
import { useDispatch, useSelector } from "react-redux";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ReactSelect } from "@/components/ui/react-select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Pipeline } from "@/api/rtk/pipelines-api";
import { PipelineStageName } from "@/api/rtk/pipeline-stage-names-api";
import { AppDispatch } from "@/store";
import type { PipelineStageKind } from "@/api/rtk/pipelines-api";
import {
  selectAddStageDialog,
  closeAddDialog,
  setAddPipelineId,
  setAddName,
  setAddStageType,
} from "@/store/slices/add-stage-slice";

interface AddStageDialogProps {
  pipelines: Pipeline[];
  adding: boolean;
  onSave: (e: React.FormEvent) => void;
}

export function AddStageDialog({
  pipelines,
  adding,
  onSave,
}: AddStageDialogProps) {
  const dispatch = useDispatch<AppDispatch>();
  const addState = useSelector(selectAddStageDialog);

  const handleOpenChange = (open: boolean) => {
    if (!open) {
      dispatch(closeAddDialog());
    }
  };

  React.useEffect(() => {
    if (addState.open && pipelines.length && !addState.addPipelineId) {
      dispatch(setAddPipelineId(pipelines[0].id));
    }
  }, [addState.open, pipelines, addState.addPipelineId, dispatch]);

  return (
    <Dialog open={addState.open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[420px] rounded-2xl">
        <DialogHeader>
          <DialogTitle className="font-['Lexend']">Add stage</DialogTitle>
          <DialogDescription>
            Appends a new stage at the end of the selected pipeline (admin
            only).
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={onSave} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="add-stage-pipeline">Pipeline</Label>
            <ReactSelect
              id="add-stage-pipeline"
              value={addState.addPipelineId || ""}
              onValueChange={(value) => dispatch(setAddPipelineId(value))}
              options={pipelines.map((pipeline) => ({
                value: pipeline.id,
                label: pipeline.name,
              }))}
              placeholder="Select pipeline"
              aria-label="Pipeline"
              triggerClassName="rounded-xl"
              contentClassName="rounded-xl"
            />
          </div>


          <div className="space-y-2">
            <Label htmlFor="add-stage-name">Name</Label>
            <Input
              id="add-stage-name"
              className="rounded-xl"
              value={addState.addName}
              onChange={(e) => dispatch(setAddName(e.target.value))}
              placeholder="Enter stage name"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="add-stage-type">Stage type</Label>
            <ReactSelect
              id="add-stage-type"
              value={addState.addStageType}
              onValueChange={(value) =>
                dispatch(setAddStageType(value as PipelineStageKind))
              }
              options={[
                { value: "Lead", label: "Lead" },
                { value: "Deal", label: "Deal" },
              ]}
              aria-label="Stage type"
              triggerClassName="rounded-xl"
              contentClassName="rounded-xl"
            />
            <p className="text-[11px] text-gray-500">
              Lead stages appear on the Leads pipeline; Deal stages are for the
              separate Deal module.
            </p>
          </div>

          <DialogFooter className="gap-2 sm:gap-3">
            <Button
              type="button"
              variant="ghost"
              className="rounded-xl"
              onClick={() => dispatch(closeAddDialog())}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              className="rounded-xl bg-accent"
              disabled={adding || !addState.addPipelineId}
            >
              {adding ? "Adding..." : "Add stage"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
