"use client";

import { useCallback, useEffect, useState } from "react";
import { Boxes, Plus, Pencil, Trash2, Target } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Badge, Input, Select, FormField, EmptyState, Skeleton } from "@/components/ui";
import { Modal, useConfirm } from "@/components/modal";
import { useToast } from "@/components/toast";

type Campaign = {
  id: string;
  name: string;
  matchType: string;
  matchValue: string;
  commissionType: string;
  commissionValue: number;
  active: boolean;
};

type Goal = {
  id: string;
  name: string;
  eventKey: string;
  model: string;
  commissionType: string;
  commissionValue: number;
  isPrimary: boolean;
  synced: boolean;
};

const emptyGoal = { name: "", model: "CPA", commissionType: "FLAT", commissionValue: "" };
type GoalForm = typeof emptyGoal;

const emptyForm = { name: "", matchType: "VENDOR", matchValue: "", commissionType: "PERCENT", commissionValue: "", active: true };
type Form = typeof emptyForm;

const MATCH_HINT: Record<string, string> = {
  VENDOR: "Products whose Shopify Vendor equals this",
  TAG: "Orders/products with this tag",
  PRODUCT: "Products whose title contains this",
  ALL: "Every product (catch-all)",
};

export default function CampaignsPage() {
  const toast = useToast();
  const confirm = useConfirm();
  const [rows, setRows] = useState<Campaign[] | null>(null);
  const [open, setOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<Form>(emptyForm);
  const [busy, setBusy] = useState(false);

  // Goals (conversion events) per campaign
  const [goalsFor, setGoalsFor] = useState<Campaign | null>(null);
  const [goals, setGoals] = useState<Goal[] | null>(null);
  const [goalForm, setGoalForm] = useState<GoalForm>(emptyGoal);
  const [goalBusy, setGoalBusy] = useState(false);

  const load = useCallback(async () => setRows(await api.get("/admin/campaigns")), []);
  useEffect(() => {
    load();
  }, [load]);

  const set = (patch: Partial<Form>) => setForm((f) => ({ ...f, ...patch }));
  const setGoal = (patch: Partial<GoalForm>) => setGoalForm((f) => ({ ...f, ...patch }));

  const openGoals = async (c: Campaign) => {
    setGoalsFor(c);
    setGoals(null);
    setGoalForm(emptyGoal);
    setGoals(await api.get(`/admin/campaigns/${c.id}/goals`));
  };

  const addGoal = async () => {
    if (!goalsFor) return;
    if (!goalForm.name.trim()) return toast.error("Enter a goal name.");
    setGoalBusy(true);
    try {
      await api.post(`/admin/campaigns/${goalsFor.id}/goals`, goalForm);
      toast.success("Goal added.");
      setGoalForm(emptyGoal);
      setGoals(await api.get(`/admin/campaigns/${goalsFor.id}/goals`));
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setGoalBusy(false);
    }
  };

  const removeGoal = async (g: Goal) => {
    if (!goalsFor) return;
    await api.del(`/admin/campaigns/${goalsFor.id}/goals/${g.id}`);
    setGoals(await api.get(`/admin/campaigns/${goalsFor.id}/goals`));
  };

  const openCreate = () => {
    setEditingId(null);
    setForm(emptyForm);
    setOpen(true);
  };
  const openEdit = (c: Campaign) => {
    setEditingId(c.id);
    setForm({
      name: c.name,
      matchType: c.matchType,
      matchValue: c.matchValue,
      commissionType: c.commissionType,
      commissionValue: c.commissionValue.toString(),
      active: c.active,
    });
    setOpen(true);
  };

  const save = async () => {
    if (!form.name.trim()) {
      toast.error("Enter a campaign name.");
      return;
    }
    if (form.matchType !== "ALL" && !form.matchValue.trim()) {
      toast.error("Enter what identifies this brand's products.");
      return;
    }
    setBusy(true);
    try {
      if (editingId) {
        await api.put(`/admin/campaigns/${editingId}`, form);
        toast.success("Campaign updated.");
      } else {
        await api.post("/admin/campaigns", form);
        toast.success("Campaign created.");
      }
      setOpen(false);
      load();
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const remove = async (c: Campaign) => {
    if (!(await confirm({ title: `Delete "${c.name}"?`, message: "Attributions already recorded stay; new orders won't match this campaign.", tone: "danger", confirmText: "Delete" }))) return;
    await api.del(`/admin/campaigns/${c.id}`);
    toast.info("Campaign deleted.");
    load();
  };

  return (
    <div className="max-w-4xl">
      <PageHeader
        title="Campaigns"
        subtitle="Run multiple brands from one store — each order is split to the right campaign"
        actions={<Button icon={<Plus className="h-4 w-4" />} onClick={openCreate}>New campaign</Button>}
      />

      <Card title="Your campaigns" subtitle="Products are matched to a campaign by Shopify vendor / tag / product">
        {!rows ? (
          <Skeleton className="h-28" />
        ) : rows.length === 0 ? (
          <EmptyState icon={<Boxes className="h-6 w-6" />} title="No campaigns yet" description="Create a campaign per brand (e.g. Mamaearth, The Derma Co) to split sales in one store." />
        ) : (
          <ul className="divide-y divide-gray-50">
            {rows.map((c) => (
              <li key={c.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
                <div className="flex items-center gap-3">
                  <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-[var(--brand-50)] text-[var(--brand)]"><Boxes className="h-5 w-5" /></span>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-gray-900">{c.name}</span>
                      {!c.active && <Badge tone="neutral">Paused</Badge>}
                    </div>
                    <div className="text-xs text-gray-500">
                      <span className="font-mono">{c.matchType}={c.matchValue || "—"}</span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Badge tone="brand">{c.commissionType === "FLAT" ? `₹${c.commissionValue}` : `${c.commissionValue}%`}</Badge>
                  <button onClick={() => openGoals(c)} title="Goals / events" className="inline-flex items-center gap-1 rounded-lg border border-gray-300 px-2 py-1.5 text-xs text-gray-600 hover:bg-gray-50"><Target className="h-3.5 w-3.5" /> Goals</button>
                  <button onClick={() => openEdit(c)} className="rounded-lg border border-gray-300 p-1.5 text-gray-500 hover:bg-gray-50"><Pencil className="h-3.5 w-3.5" /></button>
                  <button onClick={() => remove(c)} className="rounded-lg border border-gray-300 p-1.5 text-gray-500 hover:bg-red-50 hover:text-red-600"><Trash2 className="h-3.5 w-3.5" /></button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </Card>

      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={editingId ? "Edit campaign" : "New campaign"}
        footer={<><Button variant="secondary" onClick={() => setOpen(false)}>Cancel</Button><Button onClick={save} loading={busy}>{editingId ? "Save changes" : "Create campaign"}</Button></>}
      >
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <FormField label="Campaign / brand name" required>
              <Input value={form.name} onChange={(e) => set({ name: e.target.value })} placeholder="e.g. Mamaearth" />
            </FormField>
          </div>
          <FormField label="Match products by">
            <Select value={form.matchType} onChange={(e) => set({ matchType: e.target.value })}>
              <option value="VENDOR">Shopify Vendor</option>
              <option value="TAG">Tag</option>
              <option value="PRODUCT">Product title contains</option>
              <option value="ALL">All products</option>
            </Select>
          </FormField>
          <FormField label={form.matchType === "ALL" ? "—" : "Value"} hint={MATCH_HINT[form.matchType]}>
            <Input value={form.matchValue} onChange={(e) => set({ matchValue: e.target.value })} disabled={form.matchType === "ALL"} placeholder={form.matchType === "TAG" ? "e.g. mamaearth" : "e.g. Mamaearth"} />
          </FormField>
          <FormField label="Commission type">
            <Select value={form.commissionType} onChange={(e) => set({ commissionType: e.target.value })}>
              <option value="PERCENT">Percent</option>
              <option value="FLAT">Flat ₹</option>
            </Select>
          </FormField>
          <FormField label="Commission value" required>
            <Input type="number" min={0} value={form.commissionValue} onChange={(e) => set({ commissionValue: e.target.value })} placeholder="e.g. 10" />
          </FormField>
        </div>
      </Modal>

      {/* Goals / conversion events */}
      <Modal
        open={!!goalsFor}
        onClose={() => setGoalsFor(null)}
        title={goalsFor ? `Goals — ${goalsFor.name}` : "Goals"}
        footer={<Button variant="secondary" onClick={() => setGoalsFor(null)}>Done</Button>}
      >
        <p className="mb-3 text-sm text-gray-500">
          The primary <b>Sale</b> goal is the campaign&apos;s own commission
          {goalsFor ? <> (<span className="font-mono">{goalsFor.commissionType === "FLAT" ? `₹${goalsFor.commissionValue}` : `${goalsFor.commissionValue}%`}</span>)</> : null}.
          Add extra events (Lead, Signup, First-order bonus…) with their own payout.
        </p>

        {goals === null ? (
          <Skeleton className="h-20" />
        ) : goals.filter((g) => !g.isPrimary).length === 0 ? (
          <p className="mb-4 rounded-lg bg-gray-50 px-3 py-2 text-sm text-gray-500">No extra goals yet.</p>
        ) : (
          <ul className="mb-4 divide-y divide-gray-50">
            {goals.filter((g) => !g.isPrimary).map((g) => (
              <li key={g.id} className="flex items-center justify-between gap-2 py-2">
                <div>
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-900">{g.name} <Badge tone="neutral">{g.model}</Badge>{!g.synced && <Badge tone="neutral">not synced</Badge>}</div>
                  <div className="font-mono text-xs text-gray-500">{g.commissionType === "FLAT" ? `₹${g.commissionValue}` : `${g.commissionValue}%`}</div>
                </div>
                <button onClick={() => removeGoal(g)} className="rounded-lg border border-gray-300 p-1.5 text-gray-500 hover:bg-red-50 hover:text-red-600"><Trash2 className="h-3.5 w-3.5" /></button>
              </li>
            ))}
          </ul>
        )}

        <div className="rounded-xl border border-gray-200 p-3">
          <div className="mb-2 text-sm font-medium text-gray-700">Add a goal</div>
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <FormField label="Event name"><Input value={goalForm.name} onChange={(e) => setGoal({ name: e.target.value })} placeholder="e.g. Newsletter signup" /></FormField>
            </div>
            <FormField label="Model">
              <Select value={goalForm.model} onChange={(e) => setGoal({ model: e.target.value })}>
                <option value="CPA">CPA — per action</option>
                <option value="CPL">CPL — per lead</option>
                <option value="CPI">CPI — per install</option>
                <option value="CPS">CPS — per sale</option>
                <option value="CPM">CPM — per 1000 views</option>
              </Select>
            </FormField>
            <FormField label="Payout type">
              <Select value={goalForm.commissionType} onChange={(e) => setGoal({ commissionType: e.target.value })}>
                <option value="FLAT">Flat ₹</option>
                <option value="PERCENT">Percent</option>
              </Select>
            </FormField>
            <FormField label="Payout value"><Input type="number" min={0} value={goalForm.commissionValue} onChange={(e) => setGoal({ commissionValue: e.target.value })} placeholder="e.g. 50" /></FormField>
            <div className="flex items-end"><Button onClick={addGoal} loading={goalBusy} icon={<Plus className="h-4 w-4" />}>Add goal</Button></div>
          </div>
        </div>
      </Modal>
    </div>
  );
}
