import { useMemo } from "react";
import { Link } from "@inertiajs/react";
import { useQuery } from "@tanstack/react-query";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Undo2, ScrollText, Wallet, FileText, ExternalLink } from "lucide-react";
import { format } from "date-fns";

interface Props {
  companyId: string;
}

const fmtMoney = (cents: number) =>
  `£${(cents / 100).toLocaleString("en-GB", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

interface OrderRow {
  id: string;
  created_at: string;
  start_date: string;
  refund_cents: number;
  refund_reason: string | null;
  refund_status: string | null;
  status: string;
  price_cents: number;
  payment_method: string;
  num_delegates: number;
  customer_name: string;
  courses?: { title: string } | null;
  course?: { title: string } | null;
}

interface CreditNoteRow {
  id: string;
  reference: string;
  amount_cents: number;
  balance_cents: number;
  status: "active" | "spent" | "cancelled" | "expired";
  reason: string | null;
  issued_at: string;
  expires_at: string | null;
  source_order: { id: string; course_title: string | null; start_date: string | null } | null;
  user: { id: string; name: string; email: string } | null;
}

interface CreditNotesResponse {
  credit_notes: CreditNoteRow[];
  totals: {
    count: number;
    active_count: number;
    active_balance_cents: number;
    issued_total_cents: number;
    redeemed_total_cents: number;
  };
}

const statusVariant = (s: string): "default" | "secondary" | "destructive" | "outline" => {
  switch (s) {
    case "active": return "default";
    case "spent": return "secondary";
    case "cancelled": return "destructive";
    case "expired": return "outline";
    default: return "outline";
  }
};

const CompanyRefundsTab = ({ companyId }: Props) => {
  const { data: orders, isLoading: ordersLoading } = useQuery({
    queryKey: ["company-refunded-orders", companyId],
    queryFn: async (): Promise<OrderRow[]> => {
      const res = await fetch(`/api/admin/orders?company_id=${encodeURIComponent(companyId)}`);
      if (!res.ok) return [];
      return res.json();
    },
  });

  const { data: notesData, isLoading: notesLoading } = useQuery<CreditNotesResponse>({
    queryKey: ["company-credit-notes", companyId],
    queryFn: async () => {
      const res = await fetch(`/api/admin/credit-notes?company_id=${encodeURIComponent(companyId)}`);
      if (!res.ok) return { credit_notes: [], totals: { count: 0, active_count: 0, active_balance_cents: 0, issued_total_cents: 0, redeemed_total_cents: 0 } };
      return res.json();
    },
  });

  // Show any order that has a non-zero refund OR was cancelled/refunded.
  const refundedOrders = useMemo(() => {
    return (orders ?? []).filter(
      (o) => (o.refund_cents ?? 0) > 0 || o.status === "refunded" || o.status === "cancelled",
    );
  }, [orders]);

  const totals = useMemo(() => {
    const refundedTotal = refundedOrders.reduce((s, o) => s + (o.refund_cents ?? 0), 0);
    return {
      refundedTotal,
      refundedCount: refundedOrders.length,
      activeBalance: notesData?.totals.active_balance_cents ?? 0,
      activeCount: notesData?.totals.active_count ?? 0,
      issuedTotal: notesData?.totals.issued_total_cents ?? 0,
      redeemedTotal: notesData?.totals.redeemed_total_cents ?? 0,
    };
  }, [refundedOrders, notesData]);

  const notes = notesData?.credit_notes ?? [];

  return (
    <div className="space-y-6">
      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-card border border-border rounded-xl p-4">
          <div className="flex items-center gap-2 text-muted-foreground text-xs mb-1">
            <Undo2 className="w-3.5 h-3.5" /> Total Refunded
          </div>
          <p className="text-2xl font-bold text-foreground">{fmtMoney(totals.refundedTotal)}</p>
          <p className="text-xs text-muted-foreground mt-1">{totals.refundedCount} order{totals.refundedCount === 1 ? "" : "s"}</p>
        </div>
        <div className="bg-card border border-border rounded-xl p-4">
          <div className="flex items-center gap-2 text-muted-foreground text-xs mb-1">
            <Wallet className="w-3.5 h-3.5" /> Credit Available
          </div>
          <p className="text-2xl font-bold text-foreground">{fmtMoney(totals.activeBalance)}</p>
          <p className="text-xs text-muted-foreground mt-1">{totals.activeCount} active note{totals.activeCount === 1 ? "" : "s"}</p>
        </div>
        <div className="bg-card border border-border rounded-xl p-4">
          <div className="flex items-center gap-2 text-muted-foreground text-xs mb-1">
            <ScrollText className="w-3.5 h-3.5" /> Notes Issued
          </div>
          <p className="text-2xl font-bold text-foreground">{fmtMoney(totals.issuedTotal)}</p>
        </div>
        <div className="bg-card border border-border rounded-xl p-4">
          <div className="flex items-center gap-2 text-muted-foreground text-xs mb-1">
            <FileText className="w-3.5 h-3.5" /> Redeemed
          </div>
          <p className="text-2xl font-bold text-foreground">{fmtMoney(totals.redeemedTotal)}</p>
        </div>
      </div>

      {/* Refunded orders */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-border flex items-center justify-between">
          <h2 className="text-base font-semibold text-foreground flex items-center gap-2">
            <Undo2 className="w-4 h-4" /> Refunded Bookings
          </h2>
          <span className="text-xs text-muted-foreground">{refundedOrders.length} record{refundedOrders.length === 1 ? "" : "s"}</span>
        </div>
        {ordersLoading ? (
          <p className="text-muted-foreground text-center py-8">Loading…</p>
        ) : refundedOrders.length === 0 ? (
          <p className="text-muted-foreground text-center py-8">No refunds yet.</p>
        ) : (
          <Table className="text-sm">
            <TableHeader>
              <TableRow>
                <TableHead>Order Date</TableHead>
                <TableHead>Course</TableHead>
                <TableHead>Customer</TableHead>
                <TableHead>Payment</TableHead>
                <TableHead className="text-right">Refunded</TableHead>
                <TableHead>Reason</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {refundedOrders.map((o) => (
                <TableRow key={o.id}>
                  <TableCell className="whitespace-nowrap text-xs">
                    {format(new Date(o.created_at), "dd MMM yy")}
                  </TableCell>
                  <TableCell className="font-medium">{o.courses?.title || o.course?.title || "—"}</TableCell>
                  <TableCell className="text-xs">{o.customer_name}</TableCell>
                  <TableCell className="capitalize text-xs">{o.payment_method}</TableCell>
                  <TableCell className="text-right font-semibold whitespace-nowrap">
                    {fmtMoney(o.refund_cents ?? 0)}
                    {(o.refund_cents ?? 0) > 0 && (o.refund_cents ?? 0) < o.price_cents && (
                      <span className="text-muted-foreground text-xs ml-1">/ {fmtMoney(o.price_cents)}</span>
                    )}
                  </TableCell>
                  <TableCell className="text-xs text-muted-foreground max-w-[260px] truncate" title={o.refund_reason ?? ""}>
                    {o.refund_reason || <span className="italic">—</span>}
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={o.status === "cancelled" ? "destructive" : "secondary"}
                      className="capitalize"
                    >
                      {o.status}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </div>

      {/* Credit notes */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-border flex items-center justify-between">
          <h2 className="text-base font-semibold text-foreground flex items-center gap-2">
            <ScrollText className="w-4 h-4" /> Credit Notes
          </h2>
          <span className="text-xs text-muted-foreground">{notes.length} note{notes.length === 1 ? "" : "s"}</span>
        </div>
        {notesLoading ? (
          <p className="text-muted-foreground text-center py-8">Loading…</p>
        ) : notes.length === 0 ? (
          <p className="text-muted-foreground text-center py-8">No credit notes for this company.</p>
        ) : (
          <Table className="text-sm">
            <TableHeader>
              <TableRow>
                <TableHead>Reference</TableHead>
                <TableHead>Issued</TableHead>
                <TableHead>Source Booking</TableHead>
                <TableHead className="text-right">Amount</TableHead>
                <TableHead className="text-right">Balance</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Reason</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {notes.map((n) => (
                <TableRow key={n.id}>
                  <TableCell className="font-mono text-xs">{n.reference}</TableCell>
                  <TableCell className="whitespace-nowrap text-xs">
                    {format(new Date(n.issued_at), "dd MMM yy")}
                  </TableCell>
                  <TableCell className="text-xs">
                    {n.source_order ? (
                      <Link
                        href={`/admin/orders?id=${encodeURIComponent(n.source_order.id)}`}
                        className="text-primary hover:underline inline-flex items-center gap-1"
                      >
                        {n.source_order.course_title || "View order"}
                        <ExternalLink className="w-3 h-3" />
                      </Link>
                    ) : (
                      <span className="text-muted-foreground italic">—</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right whitespace-nowrap">{fmtMoney(n.amount_cents)}</TableCell>
                  <TableCell className="text-right whitespace-nowrap font-semibold">{fmtMoney(n.balance_cents)}</TableCell>
                  <TableCell>
                    <Badge variant={statusVariant(n.status)} className="capitalize">{n.status}</Badge>
                  </TableCell>
                  <TableCell className="text-xs text-muted-foreground max-w-[240px] truncate" title={n.reason ?? ""}>
                    {n.reason || <span className="italic">—</span>}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </div>
    </div>
  );
};

export default CompanyRefundsTab;
