import { createSignal, createMemo, onMount, Show, For } from "solid-js";

const API = "";

function getToken(): string {
  return typeof sessionStorage !== "undefined"
    ? sessionStorage.getItem("nxtgauge_admin_access_token") || ""
    : "";
}

function authHeaders(): Record<string, string> {
  const token = getToken();
  return {
    Accept: "application/json",
    "Content-Type": "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

const ROLE_OPTIONS = [
  "company",
  "customer",
  "job_seeker",
  "photographer",
  "video_editor",
  "graphic_designer",
  "social_media_manager",
  "fitness_trainer",
  "catering_services",
  "makeup_artist",
  "tutor",
  "developer",
];

type Coupon = {
  id: string;
  code: string;
  title: string;
  type: "PERCENT" | "FIXED";
  value: number;
  min_order_amount: number;
  used_count: number;
  usage_limit?: number;
  is_active: boolean;
  role_keys: string[];
};

const defaultForm = () => ({
  id: "",
  code: "",
  title: "",
  type: "PERCENT" as "PERCENT" | "FIXED",
  value: 10,
  min_order_amount: 0,
  max_uses: "",
  applies_to: "ALL" as "ALL" | "ROLE",
  role_keys: ["company", "customer"] as string[],
});

export default function CouponPage() {
  const [coupons, setCoupons] = createSignal<Coupon[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [loadError, setLoadError] = createSignal("");
  const [activeTab, setActiveTab] = createSignal<"list" | "create">("list");
  const [form, setForm] = createSignal(defaultForm());
  const [saving, setSaving] = createSignal(false);
  const [toggling, setToggling] = createSignal("");
  const [formError, setFormError] = createSignal("");

  // Filters
  const [search, setSearch] = createSignal("");
  const [statusFilter, setStatusFilter] = createSignal("all");
  const [sortBy, setSortBy] = createSignal<"newest" | "oldest" | "code_asc" | "code_desc">(
    "newest"
  );
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const load = async () => {
    setLoading(true);
    setLoadError("");
    try {
      const res = await fetch(`${API}/api/admin/coupons`, {
        headers: authHeaders(),
        credentials: "include",
      });
      if (!res.ok) throw new Error(`Request failed (${res.status})`);
      const data = await res.json();
      setCoupons(Array.isArray(data) ? data : (data.coupons ?? []));
    } catch (err: any) {
      setLoadError(err.message || "Could not load coupons.");
      setCoupons([]);
    } finally {
      setLoading(false);
    }
  };

  onMount(() => void load());

  const filteredCoupons = createMemo(() => {
    let r = coupons();
    const q = search().toLowerCase();
    if (q)
      {r = r.filter(
        (c) => c.code.toLowerCase().includes(q) || (c.title || "").toLowerCase().includes(q)
      );}
    if (statusFilter() === "active") r = r.filter((c) => c.is_active);
    if (statusFilter() === "inactive") r = r.filter((c) => !c.is_active);
    const sorted = [...r];
    sorted.sort((a, b) => {
      if (sortBy() === "oldest") return String(a.id || "").localeCompare(String(b.id || ""));
      if (sortBy() === "code_asc") return String(a.code || "").localeCompare(String(b.code || ""));
      if (sortBy() === "code_desc") return String(b.code || "").localeCompare(String(a.code || ""));
      return String(b.id || "").localeCompare(String(a.id || ""));
    });
    r = sorted;
    return r;
  });

  const exportCsv = () => {
    const headers = ["Code", "Title", "Type", "Value", "Max Uses", "Status"];
    const rows = filteredCoupons().map((item) => [
      item.code,
      item.title || "",
      item.type,
      item.type === "PERCENT" ? `${item.value}%` : `₹${item.value}`,
      item.usage_limit != null ? String(item.usage_limit) : "—",
      item.is_active ? "Active" : "Inactive",
    ]);
    const csv = [headers, ...rows]
      .map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(","))
      .join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "coupon-management.csv";
    link.click();
    URL.revokeObjectURL(url);
  };

  const resetForm = () => {
    setForm(defaultForm());
    setFormError("");
  };

  const startEdit = (coupon: Coupon) => {
    setForm({
      id: coupon.id,
      code: coupon.code,
      title: coupon.title || "",
      type: coupon.type,
      value: coupon.value,
      min_order_amount: coupon.min_order_amount || 0,
      max_uses: coupon.usage_limit != null ? String(coupon.usage_limit) : "",
      applies_to: 'ALL' as "ALL" | "ROLE",
      role_keys: Array.isArray(coupon.role_keys) ? coupon.role_keys : [],
    });
    setActiveTab("create");
  };

  const toggleRole = (role: string) => {
    const current = form().role_keys;
    if (current.includes(role)) {
      setForm({ ...form(), role_keys: current.filter((r) => r !== role) });
    } else {
      setForm({ ...form(), role_keys: [...current, role] });
    }
  };

  const handleSave = async (e: Event) => {
    e.preventDefault();
    try {
      setSaving(true);
      setFormError("");
      const f = form();
      const body: Record<string, unknown> = {
        code: f.code.toUpperCase(),
        title: f.title,
        discount_type: f.type,
        discount_value: Number(f.value),
        applies_to: f.applies_to,
        min_order_amount: Number(f.min_order_amount),
        role_keys: f.role_keys,
      };
      if (f.max_uses) body.max_uses = Number(f.max_uses);

      const url = f.id ? `${API}/api/admin/coupons/${f.id}` : `${API}/api/admin/coupons`;
      const method = f.id ? "PATCH" : "POST";
      const res = await fetch(url, {
        method,
        headers: authHeaders(),
        credentials: "include",
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error("Failed to save coupon");
      resetForm();
      await load();
      setActiveTab("list");
    } catch (err: unknown) {
      setFormError(err instanceof Error ? err.message : "Failed to save");
    } finally {
      setSaving(false);
    }
  };

  const handleToggle = async (coupon: Coupon) => {
    try {
      setToggling(coupon.id);
      const res = await fetch(`${API}/api/admin/coupons/${coupon.id}`, {
        method: "PATCH",
        headers: authHeaders(),
        credentials: "include",
        body: JSON.stringify({ is_active: !coupon.is_active }),
      });
      if (!res.ok) throw new Error("Failed to toggle");
      await load();
    } catch {
      // ignore
    } finally {
      setToggling("");
    }
  };

  return (
    <div class="w-full space-y-6 pb-8">
      <div style="margin-bottom:1.5rem">
        <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Coupon Management</h1>
        <p class="mt-1 text-[14px] text-[#6B7280]">Reusable coupon codes for package checkout</p>
      </div>

      {/* Tabs */}
      <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
        <button
          type="button"
          class={
            activeTab() === "list"
              ? "py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium"
              : "py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors"
          }
          onClick={() => setActiveTab("list")}
        >
          Coupons
        </button>
        <button
          type="button"
          class={
            activeTab() === "create"
              ? "py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium"
              : "py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors"
          }
          onClick={() => {
            resetForm();
            setActiveTab("create");
          }}
        >
          {form().id ? "Edit Coupon" : "Create Coupon"}
        </button>
      </div>

      <div>
        <Show when={activeTab() === "list"}>
          <div style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
            <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6;position:relative;z-index:20;margin-bottom:0">
              <input
                type="text"
                placeholder="Search by code or title..."
                value={search()}
                onInput={(e) => setSearch(e.currentTarget.value)}
                style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
              />

              <div style="position:relative;">
                <button
                  type="button"
                  onClick={() => {
                    setSortMenuOpen((v) => !v);
                    setFilterMenuOpen(false);
                  }}
                  style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
                >
                  <svg
                    width="13"
                    height="13"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path d="M7 4v13" />
                    <path d="m3 13 4 4 4-4" />
                    <path d="M17 20V7" />
                    <path d="m21 11-4-4-4 4" />
                  </svg>
                  Sort
                </button>
                <Show when={sortMenuOpen()}>
                  <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                    <For
                      each={
                        [
                          { key: "newest", label: "Newest First" },
                          { key: "oldest", label: "Oldest First" },
                          { key: "code_asc", label: "Code A-Z" },
                          { key: "code_desc", label: "Code Z-A" },
                        ] as {
                          key: "newest" | "oldest" | "code_asc" | "code_desc";
                          label: string;
                        }[]
                      }
                    >
                      {(item) => (
                        <button
                          type="button"
                          onClick={() => {
                            setSortBy(item.key);
                            setSortMenuOpen(false);
                          }}
                          style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === item.key ? "#FF5E13" : "#374151"};background:${sortBy() === item.key ? "#FFF1EB" : "transparent"}`}
                        >
                          {item.label}
                        </button>
                      )}
                    </For>
                  </div>
                </Show>
              </div>

              <div style="position:relative;">
                <button
                  type="button"
                  onClick={() => {
                    setFilterMenuOpen((v) => !v);
                    setSortMenuOpen(false);
                  }}
                  style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
                >
                  <svg
                    width="13"
                    height="13"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path d="M3 5h18M6 12h12M10 19h4" />
                  </svg>
                  Filters
                </button>
                <Show when={filterMenuOpen()}>
                  <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                    <For
                      each={
                        [
                          { key: "all", label: "All Status" },
                          { key: "active", label: "Active" },
                          { key: "inactive", label: "Inactive" },
                        ] as { key: string; label: string }[]
                      }
                    >
                      {(item) => (
                        <button
                          type="button"
                          onClick={() => {
                            setStatusFilter(item.key);
                            setFilterMenuOpen(false);
                          }}
                          style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === item.key ? "#FF5E13" : "#374151"};background:${statusFilter() === item.key ? "#FFF1EB" : "transparent"}`}
                        >
                          {item.label}
                        </button>
                      )}
                    </For>
                  </div>
                </Show>
              </div>

              <button
                type="button"
                onClick={exportCsv}
                style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer"
              >
                <svg
                  width="13"
                  height="13"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                  <polyline points="7 10 12 15 17 10" />
                  <line x1="12" y1="15" x2="12" y2="3" />
                </svg>
                Export
              </button>
            </div>
            <Show when={loadError()}>
              <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
                {loadError()}
              </div>
            </Show>
            <div class="table-card">
              <div class="overflow-x-auto">
                <table class="data-table w-full text-sm">
                  <thead>
                    <tr>
                      <th>Code</th>
                      <th>Title</th>
                      <th>Type</th>
                      <th>Value</th>
                      <th>Max Uses</th>
                      <th>Status</th>
                      <th class="text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <Show when={loading()}>
                      <tr>
                        <td colspan="7" style="text-align:center;padding:32px;color:#64748b">
                          Loading...
                        </td>
                      </tr>
                    </Show>
                    <Show when={!loading() && filteredCoupons().length === 0}>
                      <tr>
                        <td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">
                          No coupons found.
                        </td>
                      </tr>
                    </Show>
                    <Show when={!loading() && filteredCoupons().length > 0}>
                      <For each={filteredCoupons()}>
                        {(item) => (
                          <tr class="hover:bg-slate-50">
                            <td class="font-semibold text-slate-900" style="font-family:monospace">
                              {item.code}
                            </td>
                            <td class="text-slate-500">{item.title || "—"}</td>
                            <td class="text-slate-500">{item.type}</td>
                            <td class="text-slate-500">
                              {item.type === "PERCENT" ? `${item.value}%` : `₹${item.value}`}
                            </td>
                            <td class="text-slate-500">
                              {item.usage_limit != null ? item.usage_limit : "—"}
                            </td>
                            <td>
                              <span
                                style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${item.is_active ? "#FFD8C2" : "#D1D5DB"};background:${item.is_active ? "#FFF1EB" : "#F3F4F6"};color:${item.is_active ? "#FF5E13" : "#4B5563"};padding:2px 10px;font-size:12px;font-weight:500`}
                              >
                                <span
                                  style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${item.is_active ? "#FF5E13" : "#9CA3AF"};margin-right:5px;flex-shrink:0`}
                                />
                                {item.is_active ? "Active" : "Inactive"}
                              </span>
                            </td>
                            <td>
                              <div class="flex items-center justify-end gap-1">
                                <button
                                  class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                                  onClick={() => startEdit(item)}
                                >
                                  Edit
                                </button>
                                <button
                                  class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                                  disabled={toggling() === item.id}
                                  onClick={() => handleToggle(item)}
                                >
                                  {toggling() === item.id
                                    ? "..."
                                    : item.is_active
                                      ? "Disable"
                                      : "Enable"}
                                </button>
                              </div>
                            </td>
                          </tr>
                        )}
                      </For>
                    </Show>
                  </tbody>
                </table>
              </div>
              <Show when={!loading()}>
                <div style="padding:10px 16px;font-size:12px;color:#64748b;border-top:1px solid #f1f5f9">
                  {filteredCoupons().length} of {coupons().length} coupons
                </div>
              </Show>
            </div>
          </div>
        </Show>

        <Show when={activeTab() === "create"}>
          <section
            class="rounded-xl border border-gray-200 bg-white shadow-sm"
            style="max-width:520px"
          >
            <h2 style="margin:0 0 20px;font-size:16px;font-weight:700">
              {form().id ? "Edit Coupon" : "Create Coupon"}
            </h2>
            <Show when={formError()}>
              <div
                class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
                style="margin-bottom:12px"
              >
                {formError()}
              </div>
            </Show>
            <form onSubmit={handleSave} style="display:flex;flex-direction:column;gap:14px">
              <div class="field">
                <label>Code</label>
                <input
                  type="text"
                  value={form().code}
                  onInput={(e) => setForm({ ...form(), code: e.currentTarget.value.toUpperCase() })}
                  required
                  placeholder="e.g. SAVE10"
                  style="text-transform:uppercase"
                />
              </div>
              <div class="field">
                <label>Title</label>
                <input
                  type="text"
                  value={form().title}
                  onInput={(e) => setForm({ ...form(), title: e.currentTarget.value })}
                  required
                  placeholder="e.g. 10% off for companies"
                />
              </div>
              <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div class="field">
                  <label>Type</label>
                  <select
                    value={form().type}
                    onChange={(e) =>
                      setForm({ ...form(), type: e.currentTarget.value as "PERCENT" | "FIXED" })
                    }
                  >
                    <option value="PERCENT">Percent (%)</option>
                    <option value="FIXED">Fixed (₹)</option>
                  </select>
                </div>
                <div class="field">
                  <label>Value</label>
                  <input
                    type="number"
                    value={form().value}
                    onInput={(e) => setForm({ ...form(), value: Number(e.currentTarget.value) })}
                    required
                    min="1"
                  />
                </div>
              </div>
              <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div class="field">
                  <label>Min Order Amount (₹)</label>
                  <input
                    type="number"
                    value={form().min_order_amount}
                    onInput={(e) =>
                      setForm({ ...form(), min_order_amount: Number(e.currentTarget.value) })
                    }
                    min="0"
                    placeholder="0"
                  />
                </div>
                <div class="field">
                  <label>Max Uses (blank = unlimited)</label>
                  <input
                    type="number"
                    value={form().max_uses}
                    onInput={(e) => setForm({ ...form(), max_uses: e.currentTarget.value })}
                    min="1"
                    placeholder="Unlimited"
                  />
                </div>
                <div class="field">
                  <label>Applies To</label>
                  <select
                    value={form().applies_to}
                    onChange={(e) =>
                      setForm({ ...form(), applies_to: e.currentTarget.value as "ALL" | "ROLE" })
                    }
                  >
                    <option value="ALL">All</option>
                    <option value="ROLE">Specific Roles</option>
                  </select>
                </div>
              </div>
              <div>
                <p style="font-size:13px;font-weight:600;margin:0 0 8px;color:#1e293b">
                  Applicable Roles
                </p>
                <div style="display:flex;flex-wrap:wrap;gap:8px">
                  <For each={ROLE_OPTIONS}>
                    {(role) => {
                      const active = () => form().role_keys.includes(role);
                      return (
                        <button
                          type="button"
                          onClick={() => toggleRole(role)}
                          style={`border-radius:999px;padding:4px 14px;font-size:13px;cursor:pointer;border:1px solid ${active() ? "#fdba74" : "#cbd5e1"};background:${active() ? "#fff7ed" : "#fff"};color:${active() ? "#c2410c" : "#475569"}`}
                        >
                          {role}
                        </button>
                      );
                    }}
                  </For>
                </div>
              </div>
              <div class="actions">
                <button class="btn-primary" type="submit" disabled={saving()}>
                  {saving() ? "Saving..." : form().id ? "Update Coupon" : "Save Coupon"}
                </button>
                <Show when={form().id}>
                  <button
                    type="button"
                    class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                    onClick={resetForm}
                  >
                    Cancel Edit
                  </button>
                </Show>
              </div>
            </form>
          </section>
        </Show>
      </div>
    </div>
  );
}
