"use client";

import * as React from "react";
import { toast } from "sonner";
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 { ReactSelect } from "@/components/ui/react-select";
import { useUpsertTeamSalesTargetMutation } from "@/api/rtk/sales-targets-api";
import type { Team } from "@/api/rtk/teams-api";
import { formatTeamLabelForUi } from "@/lib/deal-display";

export type EditTeamTargetState = {
  teamId: string;
  teamName: string;
  // aeTarget is deprecated — team totals are now the sum of individual rep targets.
  aeTarget?: string;
};

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  year: number;
  month: number;
  teams: Team[];
  onSaved?: () => void;
  /** When set, updates an existing team record (for notes / BDR planned). */
  editTarget?: EditTeamTargetState | null;
};

export function CreateTeamTargetModal({
  open,
  onOpenChange,
  year,
  month,
  teams,
  onSaved,
  editTarget = null,
}: Props) {
  const isEdit = Boolean(editTarget);
  const [teamId, setTeamId] = React.useState("");
  // We no longer set a separate "team target" amount here.
  // Team totals are automatically the sum of the individual rep targets.
  const [upsert, { isLoading }] = useUpsertTeamSalesTargetMutation();

  React.useEffect(() => {
    if (!open) return;
    if (editTarget) {
      setTeamId(editTarget.teamId);
      return;
    }
    setTeamId(teams[0]?.id ?? "");
  }, [open, teams, editTarget]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!teamId) {
      toast.error("Select a team");
      return;
    }
    try {
      // We only send roleKind + any future notes/bdrMetrics.
      // targetAmount is deliberately omitted — team total is the sum of reps.
      await upsert({
        teamId,
        year,
        month,
        roleKind: "AE",
      }).unwrap();
      toast.success(isEdit ? "Team settings saved" : "Team settings saved");
      onOpenChange(false);
      onSaved?.();
    } catch {
      toast.error(
        isEdit ? "Failed to save team settings" : "Failed to save team settings",
      );
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <form onSubmit={(e) => void handleSubmit(e)}>
          <DialogHeader>
            <DialogTitle>
              {isEdit ? "Team settings" : "Team settings"}
            </DialogTitle>
            <DialogDescription>
              Team monetary targets are now automatically calculated as the sum of individual team members' targets.
              {isEdit
                ? ` You can still record notes or BDR planned metrics for ${formatTeamLabelForUi(editTarget?.teamName ?? "")}.`
                : " Use the rep assignment screen to set individual targets (adding a rep will automatically increase the team total)."}
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            {isEdit ? (
              <div className="grid gap-2">
                <Label>Team</Label>
                <p className="rounded-xl border border-border/80 bg-muted/30 px-3 py-2 text-sm font-semibold text-text">
                  {formatTeamLabelForUi(editTarget?.teamName ?? "")}
                </p>
              </div>
            ) : teams.length === 0 ? (
              <p className="text-sm text-muted-foreground">
                No teams available, or all teams already have settings for this month.
              </p>
            ) : (
              <div className="grid gap-2">
                <Label htmlFor="create-target-team">Team</Label>
                <ReactSelect
                  id="create-target-team"
                  value={teamId}
                  onValueChange={setTeamId}
                  options={teams.map((t) => ({
                    value: t.id,
                    label: formatTeamLabelForUi(t.name),
                  }))}
                  placeholder="Select team"
                  aria-label="Team"
                />
              </div>
            )}
            {/* No more "Team target ($)" input — totals are derived from rep targets. */}
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Close
            </Button>
            {(isEdit || teams.length > 0) && (
              <Button type="submit" disabled={isLoading || !teamId}>
                {isLoading ? "Saving…" : "Save"}
              </Button>
            )}
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
