"use client";

import { useState, useEffect } from "react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Quotation Settings",
    loading: "Loading settings...",
    saving: "Saving...",
    save: "Save Settings",
    saved: "Settings saved!",
    error: "Failed to save settings",
    defaults: "Defaults",
    defaultCurrency: "Default Currency",
    defaultTaxRate: "Default Tax Rate (%)",
    defaultPaymentTerms: "Payment Terms (days)",
    defaultValidDays: "Quote Validity (days)",
    penaltyConfig: "Late Penalty Configuration",
    penaltyEnabled: "Enable Late Penalties",
    penaltyType: "Penalty Type",
    percentage: "Percentage",
    flat: "Flat Amount",
    penaltyRate: "Rate / Amount",
    penaltyGraceDays: "Grace Period (days)",
    penaltyCompound: "Compound Penalties",
    penaltyMaxAmount: "Maximum Penalty",
    penaltyFrequencyDays: "Reapply Every (days)",
    reminders: "Payment Reminders",
    reminderEnabled: "Enable Reminders",
    reminderChannel: "Channel",
    email: "Email",
    whatsapp: "WhatsApp",
    both: "Both",
    reminderSchedule: "Schedule",
    beforeDue: "Before Due",
    onDue: "On Due Date",
    afterDue: "After Due",
    days: "days",
    deliveryDefaults: "Delivery Defaults",
    defaultSendImmediately: "Send to customer immediately by default",
  },
  ar: {
    title: "إعدادات عروض الأسعار",
    loading: "جاري تحميل الإعدادات...",
    saving: "جاري الحفظ...",
    save: "حفظ الإعدادات",
    saved: "تم حفظ الإعدادات!",
    error: "فشل في حفظ الإعدادات",
    defaults: "الإعدادات الافتراضية",
    defaultCurrency: "العملة الافتراضية",
    defaultTaxRate: "معدل الضريبة الافتراضي (%)",
    defaultPaymentTerms: "شروط الدفع (أيام)",
    defaultValidDays: "صلاحية عرض السعر (أيام)",
    penaltyConfig: "إعدادات غرامة التأخير",
    penaltyEnabled: "تفعيل غرامات التأخير",
    penaltyType: "نوع الغرامة",
    percentage: "نسبة مئوية",
    flat: "مبلغ ثابت",
    penaltyRate: "المعدل / المبلغ",
    penaltyGraceDays: "فترة السماح (أيام)",
    penaltyCompound: "غرامات مركبة",
    penaltyMaxAmount: "الحد الأقصى للغرامة",
    penaltyFrequencyDays: "إعادة التطبيق كل (أيام)",
    reminders: "تذكيرات الدفع",
    reminderEnabled: "تفعيل التذكيرات",
    reminderChannel: "القناة",
    email: "البريد الإلكتروني",
    whatsapp: "واتساب",
    both: "كلاهما",
    reminderSchedule: "الجدول",
    beforeDue: "قبل الاستحقاق",
    onDue: "في تاريخ الاستحقاق",
    afterDue: "بعد الاستحقاق",
    days: "أيام",
    deliveryDefaults: "إعدادات الإرسال",
    defaultSendImmediately: "إرسال للعميل فوراً بشكل افتراضي",
  },
};

const currencies = ["QAR", "SAR", "AED", "KWD", "BHD", "OMR", "USD"];

interface ReminderScheduleItem {
  trigger: "before_due" | "on_due" | "after_due";
  dayOffset: number;
}

interface Settings {
  defaultCurrency: string;
  defaultTaxRate: number;
  defaultPaymentTerms: number;
  defaultValidDays: number;
  penaltyEnabled: boolean;
  penaltyType: string;
  penaltyRate: number;
  penaltyGraceDays: number;
  penaltyCompound: boolean;
  penaltyMaxAmount: number | null;
  penaltyFrequencyDays: number;
  reminderEnabled: boolean;
  reminderChannel: string;
  reminderSchedule: ReminderScheduleItem[];
  defaultSendImmediately: boolean;
}

const defaultSettings: Settings = {
  defaultCurrency: "QAR",
  defaultTaxRate: 0,
  defaultPaymentTerms: 30,
  defaultValidDays: 30,
  penaltyEnabled: false,
  penaltyType: "PERCENTAGE",
  penaltyRate: 2,
  penaltyGraceDays: 7,
  penaltyCompound: false,
  penaltyMaxAmount: null,
  penaltyFrequencyDays: 30,
  reminderEnabled: true,
  reminderChannel: "email",
  reminderSchedule: [
    { trigger: "before_due", dayOffset: 3 },
    { trigger: "on_due", dayOffset: 0 },
    { trigger: "after_due", dayOffset: 7 },
  ],
  defaultSendImmediately: true,
};

export function QuotationSettingsPanel({ lang }: { lang: string }) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;
  const [settings, setSettings] = useState<Settings>(defaultSettings);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [savedMessage, setSavedMessage] = useState<string | null>(null);

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const res = await fetch("/api/dashboard/quotations/settings");
        const data = await res.json();
        if (data.success && data.settings) {
          setSettings({
            ...defaultSettings,
            ...data.settings,
            defaultSendImmediately:
              data.settings.defaultSendImmediately ?? true,
            reminderSchedule:
              typeof data.settings.reminderSchedule === "string"
                ? JSON.parse(data.settings.reminderSchedule)
                : data.settings.reminderSchedule ||
                  defaultSettings.reminderSchedule,
          });
        }
      } catch (err) {
        console.error("Failed to fetch settings:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchSettings();
  }, []);

  const handleSave = async () => {
    setSaving(true);
    setSavedMessage(null);
    try {
      const res = await fetchWithCSRF("/api/dashboard/quotations/settings", {
        method: "PATCH",
        body: JSON.stringify(settings),
      });
      if (res.ok) {
        setSavedMessage(labels.saved);
        setTimeout(() => setSavedMessage(null), 3000);
      } else {
        setSavedMessage(labels.error);
      }
    } catch {
      setSavedMessage(labels.error);
    } finally {
      setSaving(false);
    }
  };

  const updateScheduleOffset = (trigger: string, dayOffset: number) => {
    setSettings((prev) => ({
      ...prev,
      reminderSchedule: prev.reminderSchedule.map((s) =>
        s.trigger === trigger ? { ...s, dayOffset } : s,
      ),
    }));
  };

  if (loading) {
    return (
      <div className="py-12 text-center text-gray-500">{labels.loading}</div>
    );
  }

  return (
    <div dir={isAr ? "rtl" : "ltr"} className="space-y-6 max-w-2xl">
      <h3 className="text-lg font-semibold text-gray-900">{labels.title}</h3>

      {/* Defaults Card */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <h4 className="text-sm font-semibold text-gray-900 mb-4">
          {labels.defaults}
        </h4>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.defaultCurrency}
            </label>
            <select
              value={settings.defaultCurrency}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  defaultCurrency: e.target.value,
                }))
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              {currencies.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.defaultTaxRate}
            </label>
            <input
              type="number"
              min="0"
              max="100"
              step="0.01"
              value={settings.defaultTaxRate}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  defaultTaxRate: parseFloat(e.target.value) || 0,
                }))
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.defaultPaymentTerms}
            </label>
            <input
              type="number"
              min="1"
              value={settings.defaultPaymentTerms}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  defaultPaymentTerms: parseInt(e.target.value) || 30,
                }))
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.defaultValidDays}
            </label>
            <input
              type="number"
              min="1"
              value={settings.defaultValidDays}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  defaultValidDays: parseInt(e.target.value) || 30,
                }))
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
        </div>
      </div>

      {/* Penalty Config Card */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center justify-between mb-4">
          <h4 className="text-sm font-semibold text-gray-900">
            {labels.penaltyConfig}
          </h4>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={settings.penaltyEnabled}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  penaltyEnabled: e.target.checked,
                }))
              }
              className="sr-only peer"
            />
            <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>

        {settings.penaltyEnabled && (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {labels.penaltyType}
              </label>
              <select
                value={settings.penaltyType}
                onChange={(e) =>
                  setSettings((s) => ({ ...s, penaltyType: e.target.value }))
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="PERCENTAGE">{labels.percentage}</option>
                <option value="FLAT">{labels.flat}</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {labels.penaltyRate}
              </label>
              <input
                type="number"
                min="0"
                step="0.01"
                value={settings.penaltyRate}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    penaltyRate: parseFloat(e.target.value) || 0,
                  }))
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {labels.penaltyGraceDays}
              </label>
              <input
                type="number"
                min="0"
                value={settings.penaltyGraceDays}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    penaltyGraceDays: parseInt(e.target.value) || 0,
                  }))
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {labels.penaltyFrequencyDays}
              </label>
              <input
                type="number"
                min="1"
                value={settings.penaltyFrequencyDays}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    penaltyFrequencyDays: parseInt(e.target.value) || 30,
                  }))
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {labels.penaltyMaxAmount}
              </label>
              <input
                type="number"
                min="0"
                step="0.01"
                value={settings.penaltyMaxAmount ?? ""}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    penaltyMaxAmount: e.target.value
                      ? parseFloat(e.target.value)
                      : null,
                  }))
                }
                placeholder="—"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div className="flex items-center gap-2 pt-6">
              <input
                type="checkbox"
                id="penaltyCompound"
                checked={settings.penaltyCompound}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    penaltyCompound: e.target.checked,
                  }))
                }
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <label
                htmlFor="penaltyCompound"
                className="text-sm text-gray-700"
              >
                {labels.penaltyCompound}
              </label>
            </div>
          </div>
        )}
      </div>

      {/* Reminder Config Card */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center justify-between mb-4">
          <h4 className="text-sm font-semibold text-gray-900">
            {labels.reminders}
          </h4>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={settings.reminderEnabled}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  reminderEnabled: e.target.checked,
                }))
              }
              className="sr-only peer"
            />
            <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>

        {settings.reminderEnabled && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {labels.reminderChannel}
              </label>
              <select
                value={settings.reminderChannel}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    reminderChannel: e.target.value,
                  }))
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="email">{labels.email}</option>
                <option value="whatsapp">{labels.whatsapp}</option>
                <option value="both">{labels.both}</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                {labels.reminderSchedule}
              </label>
              <div className="space-y-2">
                {settings.reminderSchedule.map((sched) => {
                  const triggerLabel =
                    sched.trigger === "before_due"
                      ? labels.beforeDue
                      : sched.trigger === "on_due"
                        ? labels.onDue
                        : labels.afterDue;

                  return (
                    <div
                      key={sched.trigger}
                      className="flex items-center gap-3 bg-gray-50 px-3 py-2 rounded-lg"
                    >
                      <span className="text-sm text-gray-700 min-w-[120px]">
                        {triggerLabel}
                      </span>
                      {sched.trigger !== "on_due" && (
                        <div className="flex items-center gap-2">
                          <input
                            type="number"
                            min="1"
                            value={sched.dayOffset}
                            onChange={(e) =>
                              updateScheduleOffset(
                                sched.trigger,
                                parseInt(e.target.value) || 1,
                              )
                            }
                            className="w-20 px-2 py-1 border border-gray-300 rounded text-sm"
                          />
                          <span className="text-sm text-gray-500">
                            {labels.days}
                          </span>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Delivery Defaults Card */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <h4 className="text-sm font-semibold text-gray-900 mb-4">
          {labels.deliveryDefaults}
        </h4>
        <div className="flex items-center justify-between">
          <label className="text-sm text-gray-700">
            {labels.defaultSendImmediately}
          </label>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={settings.defaultSendImmediately}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  defaultSendImmediately: e.target.checked,
                }))
              }
              className="sr-only peer"
            />
            <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>
      </div>

      {/* Save Button */}
      <div className="flex items-center gap-3">
        <button
          onClick={handleSave}
          disabled={saving}
          className="px-6 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium text-sm disabled:opacity-50"
        >
          {saving ? labels.saving : labels.save}
        </button>
        {savedMessage && (
          <span
            className={`text-sm ${savedMessage === labels.saved ? "text-green-600" : "text-red-600"}`}
          >
            {savedMessage}
          </span>
        )}
      </div>
    </div>
  );
}
