"use client";

import * as React from "react";
import { CalendarDays, Loader2 } from "lucide-react";
import { toast } from "sonner";

import {
  useGetWorkingDaysSettingsQuery,
  useUpdateWorkingDaysSettingsMutation,
  type WorkingDaysMode,
} from "@/api/endpoints/org-settings-api";
import { useAuthToken } from "@/hooks/use-auth-token";
import { countWeekdaysInMonth, formatMonthYear } from "@/lib/working-days";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardHeader, FieldLabel, SettingRow } from "@/components/settings/ui";

function currentYearMonth(): { year: number; month: number } {
  const now = new Date();
  return { year: now.getFullYear(), month: now.getMonth() + 1 };
}

export function WorkingDaysSettingsTab() {
  const { token } = useAuthToken();
  const period = React.useMemo(() => currentYearMonth(), []);
  const { data, isLoading, isFetching } = useGetWorkingDaysSettingsQuery(period, {
    skip: !token,
  });
  const [updateSettings, { isLoading: saving }] =
    useUpdateWorkingDaysSettingsMutation();

  const [mode, setMode] = React.useState<WorkingDaysMode>("AUTO");
  const [manualDays, setManualDays] = React.useState("");

  React.useEffect(() => {
    if (!data) return;
    setMode(data.mode);
    setManualDays(
      data.manualWorkingDays != null ? String(data.manualWorkingDays) : "",
    );
  }, [data]);

  const autoPreview = countWeekdaysInMonth(period.year, period.month);
  const monthLabel = formatMonthYear(period.year, period.month);

  const parsedManual = Number.parseInt(manualDays, 10);
  const manualValid =
    mode !== "MANUAL" ||
    (Number.isFinite(parsedManual) && parsedManual >= 1 && parsedManual <= 31);

  const dirty =
    data != null &&
    (mode !== data.mode ||
      (mode === "MANUAL" &&
        parsedManual !== (data.manualWorkingDays ?? NaN)));

  const handleSave = async () => {
    if (mode === "MANUAL" && !manualValid) {
      toast.error("Enter a valid number of working days (1–31).");
      return;
    }

    try {
      await updateSettings({
        mode,
        ...(mode === "MANUAL" ? { manualWorkingDays: parsedManual } : {}),
      }).unwrap();
      toast.success("Working days settings saved.");
    } catch (err: unknown) {
      const message =
        err &&
        typeof err === "object" &&
        "data" in err &&
        typeof (err as { data?: unknown }).data === "string"
          ? (err as { data: string }).data
          : "Could not save working days settings.";
      toast.error(message);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-16 text-gray-400">
        <Loader2 className="h-5 w-5 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="flex items-center gap-3 mb-2">
        <div className="h-9 w-9 rounded-xl bg-indigo-50 flex items-center justify-center text-indigo-500">
          <CalendarDays size={18} />
        </div>
        <div>
          <h2 className="text-[18px] font-extrabold text-gray-900 font-['Lexend'] tracking-tight">
            Total Working Days
          </h2>
          <p className="text-[12px] text-gray-400">
            Controls month working-day totals used in revenue pacing and related reports.
          </p>
        </div>
      </div>

      <Card>
        <CardHeader
          title="Calculation mode"
          description={`Applies to ${monthLabel}. Saturdays and Sundays are excluded in automatic mode.`}
        />

        <div className="space-y-4">
          <SettingRow
            title="Automatic (weekdays only)"
            description={`Uses ${autoPreview} working days for ${monthLabel} (Mon–Fri).`}
          >
            <input
              type="radio"
              name="working-days-mode"
              checked={mode === "AUTO"}
              onChange={() => setMode("AUTO")}
              className="h-4 w-4 accent-[#6C63FF]"
              aria-label="Automatic working days"
            />
          </SettingRow>

          <SettingRow
            title="Manual override"
            description="Set a fixed total working days value for the organization."
          >
            <input
              type="radio"
              name="working-days-mode"
              checked={mode === "MANUAL"}
              onChange={() => setMode("MANUAL")}
              className="h-4 w-4 accent-[#6C63FF]"
              aria-label="Manual working days"
            />
          </SettingRow>

          {mode === "MANUAL" ? (
            <div className="pl-4 border-l-2 border-[#6C63FF]/20 ml-2">
              <FieldLabel>Total working days</FieldLabel>
              <Input
                type="number"
                min={1}
                max={31}
                value={manualDays}
                onChange={(e) => setManualDays(e.target.value)}
                className="max-w-[140px] mt-1"
                placeholder="e.g. 22"
              />
              {!manualValid && manualDays.trim() !== "" ? (
                <p className="text-[11px] text-red-500 mt-1">
                  Enter a whole number between 1 and 31.
                </p>
              ) : null}
            </div>
          ) : null}

          <div className="rounded-xl bg-[#6C63FF]/5 border border-[#6C63FF]/10 px-4 py-3 text-[12px] text-gray-600">
            <span className="font-semibold text-gray-800">Effective total: </span>
            {mode === "AUTO"
              ? autoPreview
              : manualValid
                ? parsedManual
                : "—"}{" "}
            working days
            {data?.effectiveWorkingDays != null && !dirty ? (
              <span className="text-gray-400"> (currently saved)</span>
            ) : null}
          </div>
        </div>
      </Card>

      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          disabled={saving || isFetching || !dirty}
          onClick={() => {
            if (!data) return;
            setMode(data.mode);
            setManualDays(
              data.manualWorkingDays != null ? String(data.manualWorkingDays) : "",
            );
          }}
        >
          Reset
        </Button>
        <Button
          type="button"
          disabled={saving || !dirty || (mode === "MANUAL" && !manualValid)}
          onClick={() => void handleSave()}
        >
          {saving ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin mr-2" />
              Saving…
            </>
          ) : (
            "Save changes"
          )}
        </Button>
      </div>
    </div>
  );
}
