"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Wallet, MousePointerClick, ShoppingCart, Trash2 } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, StatusBadge, Button, Input, Select, Checkbox, Textarea, FormField, Skeleton, Badge } from "@/components/ui";
import { useToast } from "@/components/toast";
import { useConfirm } from "@/components/modal";

type Detail = {
  id: string;
  name: string;
  email: string;
  socialHandle: string | null;
  website: string | null;
  status: string;
  paymentMethod: string | null;
  paymentDetails: { info?: string } | null;
  couponCode: string | null;
  couponDiscountType: string | null;
  couponDiscountValue: number | null;
  couponUsageLimitPerCustomer: number | null;
  couponMaxRedemptions: number | null;
  couponNewCustomersOnly: boolean;
  referralLink: string | null;
  commissionType: string | null;
  commissionValue: number | null;
  groupId: string | null;
  group: { id: string; name: string } | null;
  tags: string[];
  notes: string | null;
  signupData: Record<string, string> | null;
  balance: number;
  clicks: number;
  sales: number;
  orders: { orderId: string; date: string; total: number; commission: number; status: string }[];
};
type Group = { id: string; name: string };

const inr = (n: number) => "₹" + n.toLocaleString("en-IN");

export default function AffiliateDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const toast = useToast();
  const confirm = useConfirm();
  const [d, setD] = useState<Detail | null>(null);
  const [groups, setGroups] = useState<Group[]>([]);
  const [form, setForm] = useState<Record<string, string | boolean>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    const data: Detail = await api.get(`/admin/affiliates/${id}`);
    setD(data);
    setForm({
      name: data.name,
      email: data.email,
      socialHandle: data.socialHandle ?? "",
      website: data.website ?? "",
      status: data.status,
      paymentMethod: data.paymentMethod ?? "",
      paymentDetail: data.paymentDetails?.info ?? "",
      groupId: data.groupId ?? "",
      couponCode: data.couponCode ?? "",
      couponDiscountType: data.couponDiscountType ?? "PERCENT",
      couponDiscountValue: data.couponDiscountValue?.toString() ?? "",
      couponUsageLimitPerCustomer: data.couponUsageLimitPerCustomer?.toString() ?? "",
      couponMaxRedemptions: data.couponMaxRedemptions?.toString() ?? "",
      couponNewCustomersOnly: data.couponNewCustomersOnly,
      commissionType: data.commissionType ?? "",
      commissionValue: data.commissionValue?.toString() ?? "",
      tags: data.tags.join(", "),
      notes: data.notes ?? "",
    });
  }, [id]);

  useEffect(() => {
    load();
    api.get("/admin/groups").then(setGroups).catch(() => {});
  }, [load]);

  const set = (k: string, v: string | boolean) => setForm((f) => ({ ...f, [k]: v }));

  const validate = () => {
    const e: Record<string, string> = {};
    if (!String(form.name).trim()) e.name = "Name is required.";
    if (!String(form.email).trim()) e.email = "Email is required.";
    if (form.commissionType && !String(form.commissionValue).trim()) e.commissionValue = "Enter a value or clear the type.";
    if (String(form.commissionValue).trim() && Number(form.commissionValue) < 0) e.commissionValue = "Must be 0 or more.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const save = async () => {
    if (!validate()) {
      toast.error("Please fix the highlighted fields.");
      return;
    }
    setSaving(true);
    try {
      const { paymentDetail, ...rest } = form;
      await api.put(`/admin/affiliates/${id}`, {
        ...rest,
        paymentDetails: paymentDetail ? { info: paymentDetail } : null,
      });
      toast.success("Affiliate updated.");
      load();
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  const del = async () => {
    if (!d) return;
    if (!(await confirm({ title: `Delete ${d.name}?`, message: "This permanently removes the affiliate and all their sales, clicks and payouts. This cannot be undone.", tone: "danger", confirmText: "Delete affiliate" }))) return;
    try {
      await api.del(`/admin/affiliates/${id}`);
      toast.success("Affiliate deleted.");
      router.push("/admin/affiliates");
    } catch (e) {
      toast.error((e as Error).message);
    }
  };

  if (!d) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-8 w-48" />
        <div className="grid gap-4 lg:grid-cols-3">
          <Skeleton className="h-64 lg:col-span-2" />
          <Skeleton className="h-64" />
        </div>
      </div>
    );
  }

  return (
    <div>
      <Link href="/admin/affiliates" className="mb-3 inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700">
        <ArrowLeft className="h-4 w-4" /> Affiliates
      </Link>
      <PageHeader
        title={d.name}
        subtitle={d.email}
        actions={
          <>
            <StatusBadge status={d.status} />
            <Button variant="danger" icon={<Trash2 className="h-4 w-4" />} onClick={del}>Delete</Button>
            <Button onClick={save} loading={saving}>Save changes</Button>
          </>
        }
      />

      <div className="grid gap-4 lg:grid-cols-3">
        <div className="space-y-4 lg:col-span-2">
          <Card title="Profile" subtitle="Affiliate account details">
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField label="Full name" required error={errors.name}>
                <Input error={!!errors.name} value={form.name as string} onChange={(e) => set("name", e.target.value)} />
              </FormField>
              <FormField label="Email" required error={errors.email}>
                <Input error={!!errors.email} value={form.email as string} onChange={(e) => set("email", e.target.value)} />
              </FormField>
              <FormField label="Social handle">
                <Input value={form.socialHandle as string} onChange={(e) => set("socialHandle", e.target.value)} placeholder="@handle" />
              </FormField>
              <FormField label="Website">
                <Input value={form.website as string} onChange={(e) => set("website", e.target.value)} placeholder="https://…" />
              </FormField>
              <FormField label="Status">
                <Select value={form.status as string} onChange={(e) => set("status", e.target.value)}>
                  <option value="PENDING">Pending</option>
                  <option value="ACTIVE">Active</option>
                  <option value="REJECTED">Rejected</option>
                </Select>
              </FormField>
              <FormField label="Commission group">
                <Select value={form.groupId as string} onChange={(e) => set("groupId", e.target.value)}>
                  <option value="">No group (use default)</option>
                  {groups.map((g) => (
                    <option key={g.id} value={g.id}>{g.name}</option>
                  ))}
                </Select>
              </FormField>
              <FormField label="Payment method">
                <Select value={form.paymentMethod as string} onChange={(e) => set("paymentMethod", e.target.value)}>
                  <option value="">—</option>
                  <option value="STORE_CREDIT">Store credit (Shopify)</option>
                  <option value="PAYPAL">PayPal</option>
                  <option value="UPI">UPI</option>
                  <option value="BANK">Bank</option>
                </Select>
              </FormField>
              <FormField label="Payment details" hint="UPI id / account / PayPal email">
                <Input value={form.paymentDetail as string} onChange={(e) => set("paymentDetail", e.target.value)} />
              </FormField>
            </div>
          </Card>

          <Card title="Coupon" subtitle="Discount code & usage limits">
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField label="Coupon code">
                <Input value={form.couponCode as string} onChange={(e) => set("couponCode", e.target.value.toUpperCase())} className="font-mono" />
              </FormField>
              <FormField label="Customer discount">
                <div className="flex gap-2">
                  <Select value={form.couponDiscountType as string} onChange={(e) => set("couponDiscountType", e.target.value)} className="w-28">
                    <option value="PERCENT">% off</option>
                    <option value="FIXED">₹ off</option>
                  </Select>
                  <Input type="number" min={0} value={form.couponDiscountValue as string} onChange={(e) => set("couponDiscountValue", e.target.value)} placeholder="10" />
                </div>
              </FormField>
              <FormField label="Usage limit per customer" hint="Blank = unlimited">
                <Input type="number" min={0} value={form.couponUsageLimitPerCustomer as string} onChange={(e) => set("couponUsageLimitPerCustomer", e.target.value)} placeholder="e.g. 1" />
              </FormField>
              <FormField label="Max total redemptions" hint="Blank = unlimited">
                <Input type="number" min={0} value={form.couponMaxRedemptions as string} onChange={(e) => set("couponMaxRedemptions", e.target.value)} placeholder="unlimited" />
              </FormField>
              <div className="flex items-end pb-2.5">
                <Checkbox label="New customers only" checked={!!form.couponNewCustomersOnly} onChange={(e) => set("couponNewCustomersOnly", e.target.checked)} />
              </div>
            </div>
          </Card>

          <Card title="Commission override" subtitle="Leave blank to use group / default">
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField label="Type">
                <Select value={form.commissionType as string} onChange={(e) => set("commissionType", e.target.value)}>
                  <option value="">Use group / default</option>
                  <option value="PERCENT">Percent</option>
                  <option value="FLAT">Flat</option>
                </Select>
              </FormField>
              <FormField label="Value" error={errors.commissionValue}>
                <Input type="number" min={0} step="0.01" error={!!errors.commissionValue} value={form.commissionValue as string} onChange={(e) => set("commissionValue", e.target.value)} />
              </FormField>
            </div>
          </Card>

          <Card title="Admin" subtitle="Internal tags & notes">
            <FormField label="Tags" hint="Comma-separated">
              <Input value={form.tags as string} onChange={(e) => set("tags", e.target.value)} placeholder="Influencer, Customer" />
            </FormField>
            <div className="mt-4">
              <FormField label="Private note">
                <Textarea rows={3} value={form.notes as string} onChange={(e) => set("notes", e.target.value)} />
              </FormField>
            </div>
          </Card>
        </div>

        <div className="space-y-4">
          <Card title="Summary">
            <div className="grid grid-cols-3 gap-3 text-center">
              <Metric icon={<Wallet className="h-4 w-4" />} label="Balance" value={inr(d.balance)} />
              <Metric icon={<MousePointerClick className="h-4 w-4" />} label="Clicks" value={String(d.clicks)} />
              <Metric icon={<ShoppingCart className="h-4 w-4" />} label="Sales" value={String(d.sales)} />
            </div>
            {d.referralLink && (
              <div className="mt-4">
                <p className="mb-1 text-xs font-medium text-gray-500">Referral link</p>
                <div className="flex items-center gap-2">
                  <input readOnly value={d.referralLink} className="w-full truncate rounded-lg border border-gray-200 bg-gray-50 px-2 py-1.5 text-xs text-gray-600" />
                  <Button size="sm" variant="secondary" onClick={() => { navigator.clipboard?.writeText(d.referralLink!); toast.success("Link copied."); }}>Copy</Button>
                </div>
              </div>
            )}
            {d.tags.length > 0 && (
              <div className="mt-4 flex flex-wrap gap-1.5">
                {d.tags.map((t) => <Badge key={t} tone="brand">{t}</Badge>)}
              </div>
            )}
          </Card>

          {d.signupData && Object.keys(d.signupData).length > 0 && (
            <Card title="Signup info">
              <dl className="space-y-2 text-sm">
                {Object.entries(d.signupData).map(([k, v]) => (
                  <div key={k} className="flex justify-between gap-3">
                    <dt className="text-gray-500">{k}</dt>
                    <dd className="text-right font-medium text-gray-900">{String(v)}</dd>
                  </div>
                ))}
              </dl>
            </Card>
          )}

          <Card title="Recent sales">
            {d.orders.length === 0 ? (
              <p className="py-4 text-center text-sm text-gray-400">No sales yet.</p>
            ) : (
              <table className="w-full text-left text-xs">
                <tbody className="divide-y divide-gray-50">
                  {d.orders.map((o) => (
                    <tr key={o.orderId}>
                      <td className="py-2 text-gray-500">{o.date}</td>
                      <td className="text-gray-700">{inr(o.total)}</td>
                      <td className="font-medium text-green-700">{inr(o.commission)}</td>
                      <td className="text-right"><StatusBadge status={o.status} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}

function Metric({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <div className="rounded-lg bg-gray-50 p-2.5">
      <div className="mx-auto mb-1 flex h-7 w-7 items-center justify-center rounded-md bg-white text-[var(--brand)]">{icon}</div>
      <div className="text-sm font-bold text-gray-900">{value}</div>
      <div className="text-[10px] uppercase tracking-wide text-gray-400">{label}</div>
    </div>
  );
}
