import React, { useState } from "react";
import { differenceInDays } from "date-fns";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/format-currency";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "./dialog";
import { Button } from "./button";
import { DatePicker } from "./date-picker";
import { ToggleGroup, ToggleGroupItem } from "./toggle-group";
import { MoneyInputWithSlider } from "./money-input-with-slider";

type GoalPeriod = "90d" | "180d" | "360d" | "custom";

const PERIOD_OPTIONS: { id: GoalPeriod; label: string; days: number }[] = [
  { id: "90d", label: "90 Days", days: 90 },
  { id: "180d", label: "180 Days", days: 180 },
  { id: "360d", label: "360 Days", days: 360 },
  { id: "custom", label: "Custom", days: 0 },
];

const PERIOD_DAYS: Partial<Record<GoalPeriod, number>> = Object.fromEntries(
  PERIOD_OPTIONS.map((p) => [p.id, p.days]),
);

function SummaryRow({ label, value }: { label: string; value: number }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-sm text-foreground">{label}</span>
      <span className="text-sm font-semibold tabular-nums text-foreground">
        {formatCurrency(value)}
      </span>
    </div>
  );
}

export interface SavingsGoalModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Current monthly savings trend (pre-calculated) in dollars */
  currentMonthlyTrend?: number;
  /** Initial goal amount in dollars */
  defaultGoalAmount?: number;
  /** Called when user confirms the goal */
  onSave?: (goalAmount: number, periodDays: number) => void;
  className?: string;
}

export function SavingsGoalModal({
  open,
  onOpenChange,
  currentMonthlyTrend = 0,
  defaultGoalAmount = 0,
  onSave,
  className,
}: SavingsGoalModalProps) {
  const [goalAmount, setGoalAmount] = useState(defaultGoalAmount);
  const [selectedPeriod, setSelectedPeriod] = useState<GoalPeriod>("90d");
  const [customStart, setCustomStart] = useState<Date | undefined>(undefined);
  const [customEnd, setCustomEnd] = useState<Date | undefined>(undefined);

  const isCustom = selectedPeriod === "custom";
  const today = new Date();

  const periodDays = isCustom
    ? customStart && customEnd && customEnd > customStart
      ? differenceInDays(customEnd, customStart)
      : 0
    : (PERIOD_DAYS[selectedPeriod] ?? 90);

  const monthlyTarget =
    periodDays > 0 ? Math.round((goalAmount / periodDays) * 30) : 0;

  const canSave = goalAmount > 0 && (!isCustom || periodDays > 0);

  const handleSave = () => {
    onSave?.(goalAmount, periodDays);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className={cn("max-w-sm top-8 translate-y-0", className)}>
        <DialogHeader>
          <DialogTitle>Savings Target Setter</DialogTitle>
        </DialogHeader>

        <div className="flex flex-col gap-6 py-2">
          <MoneyInputWithSlider
            label="Savings Goal"
            value={goalAmount}
            min={0}
            max={200_000}
            step={500}
            onChange={setGoalAmount}
          />

          <div className="flex flex-col gap-3">
            <p className="text-sm font-medium text-foreground">End Goal Date</p>
            <ToggleGroup
              type="single"
              variant="outline"
              size="sm"
              className="w-full"
              value={[selectedPeriod]}
              onValueChange={(values) => {
                const next = values[0] as GoalPeriod | undefined;
                if (next) setSelectedPeriod(next);
              }}
            >
              {PERIOD_OPTIONS.map((option) => (
                <ToggleGroupItem
                  key={option.id}
                  value={option.id}
                  className="flex-1"
                >
                  {option.label}
                </ToggleGroupItem>
              ))}
            </ToggleGroup>

            {isCustom && (
              <div className="grid grid-cols-2 gap-2">
                <div className="flex flex-col gap-1">
                  <p className="text-xs text-muted-foreground">Start Date</p>
                  <DatePicker
                    value={customStart}
                    onChange={setCustomStart}
                    placeholder="Start date"
                    calendarProps={{ disabled: { before: today } }}
                  />
                </div>
                <div className="flex flex-col gap-1">
                  <p className="text-xs text-muted-foreground">End Date</p>
                  <DatePicker
                    value={customEnd}
                    onChange={setCustomEnd}
                    placeholder="End date"
                    calendarProps={{
                      disabled: { before: customStart ?? today },
                    }}
                  />
                </div>
              </div>
            )}
          </div>

          <div className="flex flex-col gap-3 border-t border-border pt-4">
            <SummaryRow label="Monthly Savings Target" value={monthlyTarget} />
            <SummaryRow label="Current Trend" value={currentMonthlyTrend} />
          </div>
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={!canSave}>
            Set Now
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
