"use client";

import { useState } from "react";
import { X, Plus, Loader2 } from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Create Referral Code",
    name: "Campaign Name",
    namePlaceholder: "e.g., Summer Referral Program",
    description: "Description (optional)",
    rewardType: "Reward Type",
    percentage: "Percentage Discount",
    fixed: "Fixed Amount",
    freeSession: "Free Session",
    rewardValue: "Reward Value",
    maxUses: "Max Uses (leave empty for unlimited)",
    expiresAt: "Expires At (optional)",
    create: "Create Code",
    cancel: "Cancel",
    error: "Failed to create referral code",
  },
  ar: {
    title: "إنشاء رمز إحالة",
    name: "اسم الحملة",
    namePlaceholder: "مثال: برنامج إحالة الصيف",
    description: "الوصف (اختياري)",
    rewardType: "نوع المكافأة",
    percentage: "خصم بالنسبة المئوية",
    fixed: "مبلغ ثابت",
    freeSession: "جلسة مجانية",
    rewardValue: "قيمة المكافأة",
    maxUses: "الحد الأقصى للاستخدام (اتركه فارغاً للاستخدام غير المحدود)",
    expiresAt: "تاريخ الانتهاء (اختياري)",
    create: "إنشاء الرمز",
    cancel: "إلغاء",
    error: "فشل في إنشاء رمز الإحالة",
  },
};

export default function ReferralForm({
  lang,
  onClose,
  onSuccess,
}: {
  lang: string;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [form, setForm] = useState({
    name: "",
    description: "",
    rewardType: "percentage" as "percentage" | "fixed" | "free_session",
    rewardValue: 10,
    maxUses: "",
    expiresAt: "",
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.name.trim()) return;

    setLoading(true);
    setError("");

    try {
      const res = await fetchWithCSRF("/api/dashboard/referrals", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name.trim(),
          description: form.description.trim() || null,
          rewardType: form.rewardType,
          rewardValue: form.rewardValue,
          maxUses: form.maxUses ? parseInt(form.maxUses) : null,
          expiresAt: form.expiresAt || null,
        }),
      });

      if (!res.ok) throw new Error("Failed");
      onSuccess();
      onClose();
    } catch {
      setError(labels.error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div
        className="bg-white rounded-xl shadow-xl w-full max-w-lg"
        dir={isAr ? "rtl" : "ltr"}
      >
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="text-lg font-semibold text-slate-900">
            {labels.title}
          </h3>
          <button
            onClick={onClose}
            className="p-1 hover:bg-slate-100 rounded-lg"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.name} *
            </label>
            <input
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              placeholder={labels.namePlaceholder}
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.description}
            </label>
            <input
              value={form.description}
              onChange={(e) =>
                setForm({ ...form, description: e.target.value })
              }
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.rewardType}
            </label>
            <div className="flex gap-2">
              {(
                [
                  ["percentage", labels.percentage],
                  ["fixed", labels.fixed],
                  ["free_session", labels.freeSession],
                ] as const
              ).map(([val, label]) => (
                <button
                  key={val}
                  type="button"
                  onClick={() => setForm({ ...form, rewardType: val })}
                  className={`px-3 py-1.5 text-xs rounded-lg border ${
                    form.rewardType === val
                      ? "bg-brand-green/20 border-brand-green text-brand-green"
                      : "border-slate-300 text-slate-600 hover:bg-slate-50"
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>

          {form.rewardType !== "free_session" && (
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">
                {labels.rewardValue}{" "}
                {form.rewardType === "percentage" ? "(%)" : "(QAR)"}
              </label>
              <input
                type="number"
                value={form.rewardValue}
                onChange={(e) =>
                  setForm({ ...form, rewardValue: Number(e.target.value) })
                }
                min={0}
                max={form.rewardType === "percentage" ? 100 : 10000}
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          )}

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">
                {labels.maxUses}
              </label>
              <input
                type="number"
                value={form.maxUses}
                onChange={(e) => setForm({ ...form, maxUses: e.target.value })}
                min={1}
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">
                {labels.expiresAt}
              </label>
              <input
                type="date"
                value={form.expiresAt}
                onChange={(e) =>
                  setForm({ ...form, expiresAt: e.target.value })
                }
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          </div>

          {error && (
            <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">
              {error}
            </p>
          )}

          <div className="flex gap-3 justify-end">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm p-1 hover:bg-slate-100 rounded-lg"
            >
              {labels.cancel}
            </button>
            <button
              type="submit"
              disabled={loading || !form.name.trim()}
              className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 disabled:opacity-50 text-sm"
            >
              {loading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Plus className="w-4 h-4" />
              )}
              {labels.create}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
