"use client";

import { useEffect, useState } from "react";
import { toast } from "@/lib/toast";
import { useTranslation } from "@/hooks/useTranslation";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  DingtalkAnnualLeavePlanSettings,
  getDingtalkAnnualLeavePlanSettings,
  updateDingtalkAnnualLeavePlanSettings,
  updateAnnualLeaveQuota,
} from "@/services/api/dingtalk";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  userId: string | null;
  year: number;
  fallbackName?: string;
  onSaved?: (settings: DingtalkAnnualLeavePlanSettings) => void;
};

type FormState = {
  adjustmentDays: string;
  notCountDays: string;
};

type QuotaOverride = {
  totalDays: string;
};

export function DingtalkAnnualLeavePlanSettingsDialog({
  open,
  onOpenChange,
  userId,
  year,
  fallbackName,
  onSaved,
}: Props) {
  const { t } = useTranslation();
  const texts = t.organization.dingtalkAnnualLeave;
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [data, setData] = useState<DingtalkAnnualLeavePlanSettings | null>(null);
  const [form, setForm] = useState<FormState>({
    adjustmentDays: "0",
    notCountDays: "0",
  });
  const [quotaOverride, setQuotaOverride] = useState<QuotaOverride>({ totalDays: "" });
  const [applyingQuota, setApplyingQuota] = useState(false);

  useEffect(() => {
    if (!open || !userId) return;

    let cancelled = false;
    setLoading(true);
    void getDingtalkAnnualLeavePlanSettings({ userId, year })
      .then((result) => {
        if (cancelled) return;
        setData(result);
        setForm({
          adjustmentDays: String(result.adjustmentDays ?? 0),
          notCountDays: String(result.notCountDays ?? 0),
        });
      })
      .catch((error: unknown) => {
        toast.error(getErrorMessage(error, texts.planSettingsLoadFailed));
        if (!cancelled) {
          onOpenChange(false);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [open, userId, year, onOpenChange, texts.planSettingsLoadFailed]);

  const handleSubmit = async () => {
    if (!userId) return;

    const adjustmentDays = Number(form.adjustmentDays);
    const notCountDays = Number(form.notCountDays);
    if (Number.isNaN(adjustmentDays)) {
      toast.error(texts.adjustmentDaysInvalid);
      return;
    }
    if (!Number.isInteger(notCountDays)) {
      toast.error(texts.notCountDaysInvalid);
      return;
    }

    setSaving(true);
    try {
      const result = await updateDingtalkAnnualLeavePlanSettings({
        userId,
        year,
        adjustmentDays,
        notCountDays,
        recalculate: true,
      });
      setData(result);
      setForm({
        adjustmentDays: String(result.adjustmentDays),
        notCountDays: String(result.notCountDays),
      });
      toast.success(texts.planSettingsSaveSuccess);
      onSaved?.(result);
      onOpenChange(false);
    } catch (error: unknown) {
      toast.error(getErrorMessage(error, texts.planSettingsSaveFailed));
    } finally {
      setSaving(false);
    }
  };

  const handleApplyQuota = async () => {
    if (!userId) return;
    const totalDays = Number(quotaOverride.totalDays);
    if (Number.isNaN(totalDays) || totalDays < 0) {
      toast.error("请输入有效的天数");
      return;
    }

    setApplyingQuota(true);
    try {
      const result = await updateAnnualLeaveQuota({ userId, year, totalDays });
      if (result.success && result.detail) {
        toast.success(`${result.detail.name}：${result.detail.oldDays} → ${result.detail.newDays} 天`);
        setQuotaOverride({ totalDays: "" });
        onSaved?.(data!);
      } else {
        toast.error(result.error || "调整失败");
      }
    } catch (error: unknown) {
      toast.error(getErrorMessage(error, "调整失败"));
    } finally {
      setApplyingQuota(false);
    }
  };

  const displayName = fallbackName || userId || "-";

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[640px]">
        <DialogHeader>
          <DialogTitle>{texts.planSettingsTitle}</DialogTitle>
          <DialogDescription>
            {texts.planSettingsDescription}
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="py-10 text-center text-sm" style={{ color: "#8f959e" }}>
            {texts.loading}
          </div>
        ) : (
          <div className="space-y-5">
            <div
              className="grid grid-cols-1 md:grid-cols-2 gap-4 rounded-lg p-4"
              style={{ border: "1px solid #e5e6eb", backgroundColor: "#fafafa" }}
            >
              <ReadonlyField label={t.organization.name} value={displayName} />
              <ReadonlyField label={texts.userId} value={data?.userId || userId || "-"} mono />
              <ReadonlyField label={texts.year} value={String(data?.year || year)} />
              <ReadonlyField label={texts.totalPlannedDays} value={String(data?.totalDays ?? "-")} />
              <ReadonlyField label={texts.planLastCalculatedAt} value={formatTime(data?.lastCalculatedAt, texts.notSynced)} />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>{texts.adjustmentDaysLabel}</Label>
                <Input
                  type="number"
                  step="0.5"
                  value={form.adjustmentDays}
                  onChange={(event) =>
                    setForm((prev) => ({ ...prev, adjustmentDays: event.target.value }))
                  }
                />
                <p className="text-xs" style={{ color: "#8f959e" }}>
                  {texts.adjustmentDaysHint}
                </p>
              </div>

              <div className="space-y-2">
                <Label>{texts.notCountDaysLabel}</Label>
                <Input
                  type="number"
                  step="1"
                  value={form.notCountDays}
                  onChange={(event) =>
                    setForm((prev) => ({ ...prev, notCountDays: event.target.value }))
                  }
                />
                <p className="text-xs" style={{ color: "#8f959e" }}>
                  {texts.notCountDaysHint}
                </p>
              </div>
            </div>

            {/* 直接调整钉钉额度 */}
            <div
              className="rounded-lg p-4 space-y-3"
              style={{ border: "1px solid #e5e6eb", backgroundColor: "#fff8f0" }}
            >
              <div className="text-sm font-medium" style={{ color: "#1f2329" }}>
                直接调整钉钉额度
              </div>
              <p className="text-xs" style={{ color: "#8f959e" }}>
                直接修改该员工在钉钉上 {year} 年的年假总额度，立即生效。
              </p>
              <div className="flex items-end gap-3">
                <div className="space-y-1 flex-1">
                  <Label>目标总天数</Label>
                  <Input
                    type="number"
                    step="0.5"
                    min="0"
                    placeholder="例如 10"
                    value={quotaOverride.totalDays}
                    onChange={(e) => setQuotaOverride({ totalDays: e.target.value })}
                  />
                </div>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => void handleApplyQuota()}
                  disabled={applyingQuota || !quotaOverride.totalDays}
                >
                  {applyingQuota ? "提交中..." : "立即调整"}
                </Button>
              </div>
            </div>
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
            {texts.cancel}
          </Button>
          <Button onClick={() => void handleSubmit()} disabled={loading || saving || !userId}>
            {saving ? texts.saving : texts.save}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function ReadonlyField({
  label,
  value,
  mono = false,
}: {
  label: string;
  value: string;
  mono?: boolean;
}) {
  return (
    <div className="space-y-1">
      <div className="text-xs" style={{ color: "#8f959e" }}>
        {label}
      </div>
      <div
        className={`text-sm font-medium ${mono ? "font-mono" : ""}`}
        style={{ color: "#1f2329" }}
      >
        {value}
      </div>
    </div>
  );
}

function formatTime(value: string | null | undefined, fallback: string) {
  if (!value) return fallback;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}

function getErrorMessage(error: unknown, fallback: string) {
  if (error instanceof Error && error.message) return error.message;
  return fallback;
}
