import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

export type PeriodPreset = "month" | "ytd" | "prev-year" | "custom";

const TZ_ET = "America/New_York";
const etToday = () => new Date().toLocaleDateString("en-CA", { timeZone: TZ_ET }); // YYYY-MM-DD

/** Date range for a preset (ET). Month = current calendar month to date. */
export function periodRange(preset: Exclude<PeriodPreset, "custom">): { from: string; to: string } {
  const today = etToday();
  const [y, m] = today.split("-").map(Number);
  if (preset === "month") return { from: `${today.slice(0, 7)}-01`, to: today };
  if (preset === "ytd") return { from: `${y}-01-01`, to: today };
  // prev-year
  return { from: `${y - 1}-01-01`, to: `${y - 1}-12-31` };
}

export const PERIOD_LABELS: Record<PeriodPreset, string> = {
  month: "This Month",
  ytd: "Year to Date",
  "prev-year": "Previous Year",
  custom: "Custom",
};

/**
 * Shared period control for ledgers/registers: Month (default) / YTD /
 * Previous Year / Custom. The owner holds preset+from+to state; on preset
 * change the range is recomputed and pushed up.
 */
export function PeriodPicker({
  preset, from, to, onChange, className,
}: {
  preset: PeriodPreset;
  from: string;
  to: string;
  onChange: (next: { preset: PeriodPreset; from: string; to: string }) => void;
  className?: string;
}) {
  const setPreset = (p: PeriodPreset) => {
    if (p === "custom") onChange({ preset: p, from, to });
    else onChange({ preset: p, ...periodRange(p) });
  };

  return (
    <div className={`flex flex-wrap items-end gap-3 ${className ?? ""}`}>
      <div>
        <Label className="text-xs text-muted-foreground">Period</Label>
        <Select value={preset} onValueChange={(v) => setPreset(v as PeriodPreset)}>
          <SelectTrigger className="w-40 mt-1"><SelectValue /></SelectTrigger>
          <SelectContent>
            {(Object.keys(PERIOD_LABELS) as PeriodPreset[]).map((p) => (
              <SelectItem key={p} value={p}>{PERIOD_LABELS[p]}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      {preset === "custom" && (
        <>
          <div>
            <Label className="text-xs text-muted-foreground">From</Label>
            <Input type="date" value={from} onChange={(e) => e.target.value && onChange({ preset, from: e.target.value, to })} className="w-40 mt-1" />
          </div>
          <div>
            <Label className="text-xs text-muted-foreground">To</Label>
            <Input type="date" value={to} onChange={(e) => e.target.value && onChange({ preset, to: e.target.value, from })} className="w-40 mt-1" />
          </div>
        </>
      )}
    </div>
  );
}
