"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useParams, useRouter } from "next/navigation";
import {
  ArrowLeft, FileText, Ticket, CreditCard, RefreshCw,
  CheckCircle2, Circle, MapPin, Zap, AlertTriangle,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { Input } from "@/components/ui/Input";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { formatDate, formatCurrency } from "@/lib/utils";
import api from "@/lib/api";
import { toast } from "sonner";
import type { Client, Subscription, Invoice, Ticket as TicketType, Payment, LegacyPaginatedResponse } from "@/types";

type Tab = "profile" | "subscriptions" | "invoices" | "payments" | "tickets";

const statusColor: Record<string, "success" | "warning" | "danger" | "muted"> = {
  ACTIVE: "success", active: "success",
  SUSPENDED: "warning", suspended: "warning",
  CANCELLED: "danger", cancelled: "danger",
  DISCONNECTED: "danger",
  PENDING: "muted", pending: "muted",
};

const invColor: Record<string, "success" | "warning" | "danger" | "muted"> = {
  PAID: "success", paid: "success",
  PARTIAL: "warning", partial: "warning",
  OVERDUE: "danger", overdue: "danger",
  SENT: "muted", DRAFT: "muted", VOID: "muted",
};

const channelColors: Record<string, string> = {
  CASH: "bg-green-100 text-green-700",
  GCASH: "bg-blue-100 text-blue-700",
  MAYA: "bg-purple-100 text-purple-700",
  BANK_TRANSFER: "bg-yellow-100 text-yellow-700",
  CHECK: "bg-gray-100 text-gray-700",
};

// ─── Activation Flow Types ────────────────────────────────────────────────────

interface ActivationState {
  installationTicketId: string | null;   // existing INSTALLATION ticket (OPEN/IN_PROGRESS)
  installationResolved: boolean;
  locationPinned: boolean;               // client has lat/lng set
  invoiceCreated: boolean;               // at least one invoice exists (prepaid: before activation)
  activationTicketId: string | null;     // the INSTALLATION ticket used for activation step
  activationResolved: boolean;
  clientActive: boolean;
}

// ─── Activation Flow Card ─────────────────────────────────────────────────────

function ActivationFlowCard({
  client,
  subscriptions,
  tickets,
  invoices,
  onRefresh,
}: {
  client: Client;
  subscriptions: Subscription[];
  tickets: TicketType[];
  invoices: Invoice[];
  onRefresh: () => void;
}) {
  const qc = useQueryClient();
  const [showPinModal, setShowPinModal] = useState(false);
  const [pinForm, setPinForm] = useState({ lat: String(client.lat ?? ""), lng: String(client.lng ?? "") });
  const [showActivationTicketModal, setShowActivationTicketModal] = useState(false);

  const pendingSub = subscriptions.find(s => s.status === "PENDING");
  const billingType = pendingSub?.type ?? "POSTPAID";

  // Derive state from data
  const installationTickets = tickets.filter(t => t.type === "INSTALLATION");
  const openInstallTicket = installationTickets.find(t => t.status === "OPEN" || t.status === "IN_PROGRESS");
  const resolvedInstallTickets = installationTickets.filter(t => t.status === "RESOLVED" || t.status === "CLOSED");

  // Activation ticket = an INSTALLATION ticket created after the first one is resolved
  // We identify it by: resolved install exists + there's another ticket also INSTALLATION
  const activationTicket = resolvedInstallTickets.length > 1
    ? resolvedInstallTickets[resolvedInstallTickets.length - 1]  // latest resolved = activation
    : installationTickets.find(t =>
        (t.status === "OPEN" || t.status === "IN_PROGRESS") &&
        resolvedInstallTickets.length > 0
      );

  const state: ActivationState = {
    installationTicketId: openInstallTicket?.id ?? null,
    installationResolved: resolvedInstallTickets.length > 0,
    locationPinned: !!(client.lat && client.lng),
    invoiceCreated: invoices.length > 0,
    activationTicketId: activationTicket?.id ?? null,
    activationResolved: !!(activationTicket && (activationTicket.status === "RESOLVED" || activationTicket.status === "CLOSED")),
    clientActive: client.isActive && (!pendingSub || pendingSub.status !== "PENDING"),
  };

  // PREPAID steps: resolve install → pin location → create invoice → create activation ticket → resolve → activate
  // POSTPAID steps: resolve install → pin location → create activation ticket → resolve → activate → create invoice
  const isPrepaid = billingType === "PREPAID";

  // Mutations
  const resolveInstallMutation = useMutation({
    mutationFn: async (ticketId: string) => {
      await api.patch(`/api/v1/tickets/${ticketId}`, { status: "RESOLVED" });
    },
    onSuccess: () => { toast.success("Installation ticket resolved!"); onRefresh(); qc.invalidateQueries({ queryKey: ["client-tickets", client.id] }); },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to resolve ticket"),
  });

  const pinLocationMutation = useMutation({
    mutationFn: async () => {
      const lat = parseFloat(pinForm.lat);
      const lng = parseFloat(pinForm.lng);
      if (isNaN(lat) || isNaN(lng)) throw new Error("Invalid coordinates");
      await api.patch(`/api/v1/clients/${client.id}`, { lat, lng });
    },
    onSuccess: () => {
      toast.success("Location pinned!");
      setShowPinModal(false);
      onRefresh();
      qc.invalidateQueries({ queryKey: ["client", client.id] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? e.message ?? "Failed to save location"),
  });

  const generateInvoiceMutation = useMutation({
    mutationFn: async () => {
      await api.post(`/api/v1/invoices/generate/${client.id}`, {});
    },
    onSuccess: () => {
      toast.success("Invoice generated!");
      onRefresh();
      qc.invalidateQueries({ queryKey: ["client-invoices", client.id] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to generate invoice"),
  });

  const createActivationTicketMutation = useMutation({
    mutationFn: async () => {
      await api.post("/api/v1/tickets", {
        clientId: client.id,
        subject: `Activation — ${client.firstName} ${client.lastName} (${client.accountNumber})`,
        type: "INSTALLATION",
        priority: "HIGH",
      });
    },
    onSuccess: () => {
      toast.success("Activation ticket created!");
      setShowActivationTicketModal(false);
      onRefresh();
      qc.invalidateQueries({ queryKey: ["client-tickets", client.id] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to create ticket"),
  });

  const resolveActivationMutation = useMutation({
    mutationFn: async (ticketId: string) => {
      // 1. Resolve activation ticket
      await api.patch(`/api/v1/tickets/${ticketId}`, { status: "RESOLVED" });
      // 2. Set client to active
      await api.patch(`/api/v1/clients/${client.id}`, { isActive: true });
      // 3. Activate pending subscription if any
      if (pendingSub) {
        await api.patch(`/api/v1/clients/${client.id}/subscriptions/${pendingSub.id}/activate`, {});
      }
    },
    onSuccess: () => {
      toast.success("Client activated! 🎉");
      onRefresh();
      qc.invalidateQueries({ queryKey: ["client", client.id] });
      qc.invalidateQueries({ queryKey: ["client-subscriptions", client.id] });
      qc.invalidateQueries({ queryKey: ["client-tickets", client.id] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Activation failed"),
  });

  const generatePostpaidInvoiceMutation = useMutation({
    mutationFn: async () => {
      await api.post(`/api/v1/invoices/generate/${client.id}`, {});
    },
    onSuccess: () => {
      toast.success("First month invoice generated!");
      onRefresh();
      qc.invalidateQueries({ queryKey: ["client-invoices", client.id] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to generate invoice"),
  });

  // Build steps based on billing type
  type StepStatus = "done" | "active" | "pending";

  interface Step {
    label: string;
    description: string;
    status: StepStatus;
    action?: React.ReactNode;
  }

  const steps: Step[] = isPrepaid
    ? [
        {
          label: "Resolve Installation",
          description: "Mark the installation ticket as resolved",
          status: state.installationResolved ? "done" : "active",
          action: !state.installationResolved && state.installationTicketId ? (
            <Button size="sm" onClick={() => resolveInstallMutation.mutate(state.installationTicketId!)}
              isLoading={resolveInstallMutation.isPending}>
              Resolve Ticket
            </Button>
          ) : undefined,
        },
        {
          label: "Pin Installation Location",
          description: "Save the client's GPS coordinates",
          status: state.locationPinned ? "done" : state.installationResolved ? "active" : "pending",
          action: !state.locationPinned && state.installationResolved ? (
            <Button size="sm" onClick={() => setShowPinModal(true)}>
              <MapPin className="h-3.5 w-3.5 mr-1" /> Pin Location
            </Button>
          ) : undefined,
        },
        {
          label: "Create Invoice",
          description: "Generate the first month invoice (client pays before activation)",
          status: state.invoiceCreated ? "done" : (state.installationResolved && state.locationPinned) ? "active" : "pending",
          action: !state.invoiceCreated && state.installationResolved && state.locationPinned ? (
            <Button size="sm" onClick={() => generateInvoiceMutation.mutate()}
              isLoading={generateInvoiceMutation.isPending}>
              <FileText className="h-3.5 w-3.5 mr-1" /> Generate Invoice
            </Button>
          ) : undefined,
        },
        {
          label: "Create Activation Ticket",
          description: "Open a ticket to confirm service activation",
          status: state.activationTicketId ? "done" : (state.invoiceCreated) ? "active" : "pending",
          action: !state.activationTicketId && state.invoiceCreated ? (
            <Button size="sm" onClick={() => createActivationTicketMutation.mutate()}
              isLoading={createActivationTicketMutation.isPending}>
              <Ticket className="h-3.5 w-3.5 mr-1" /> Create Ticket
            </Button>
          ) : undefined,
        },
        {
          label: "Resolve Activation → Client Active",
          description: "Resolve the activation ticket — client status will be set to Active automatically",
          status: state.clientActive ? "done" : (state.activationTicketId && !state.activationResolved) ? "active" : "pending",
          action: state.activationTicketId && !state.activationResolved && !state.clientActive ? (
            <Button size="sm" variant="primary" onClick={() => resolveActivationMutation.mutate(state.activationTicketId!)}
              isLoading={resolveActivationMutation.isPending}>
              <Zap className="h-3.5 w-3.5 mr-1" /> Resolve & Activate
            </Button>
          ) : undefined,
        },
      ]
    : [
        {
          label: "Resolve Installation",
          description: "Mark the installation ticket as resolved",
          status: state.installationResolved ? "done" : "active",
          action: !state.installationResolved && state.installationTicketId ? (
            <Button size="sm" onClick={() => resolveInstallMutation.mutate(state.installationTicketId!)}
              isLoading={resolveInstallMutation.isPending}>
              Resolve Ticket
            </Button>
          ) : undefined,
        },
        {
          label: "Pin Installation Location",
          description: "Save the client's GPS coordinates",
          status: state.locationPinned ? "done" : state.installationResolved ? "active" : "pending",
          action: !state.locationPinned && state.installationResolved ? (
            <Button size="sm" onClick={() => setShowPinModal(true)}>
              <MapPin className="h-3.5 w-3.5 mr-1" /> Pin Location
            </Button>
          ) : undefined,
        },
        {
          label: "Create Activation Ticket",
          description: "Open a ticket to confirm service activation",
          status: state.activationTicketId ? "done" : (state.installationResolved && state.locationPinned) ? "active" : "pending",
          action: !state.activationTicketId && state.installationResolved && state.locationPinned ? (
            <Button size="sm" onClick={() => createActivationTicketMutation.mutate()}
              isLoading={createActivationTicketMutation.isPending}>
              <Ticket className="h-3.5 w-3.5 mr-1" /> Create Ticket
            </Button>
          ) : undefined,
        },
        {
          label: "Resolve Activation → Client Active",
          description: "Resolve the activation ticket — client status will be set to Active automatically",
          status: state.clientActive ? "done" : (state.activationTicketId && !state.activationResolved) ? "active" : "pending",
          action: state.activationTicketId && !state.activationResolved && !state.clientActive ? (
            <Button size="sm" variant="primary" onClick={() => resolveActivationMutation.mutate(state.activationTicketId!)}
              isLoading={resolveActivationMutation.isPending}>
              <Zap className="h-3.5 w-3.5 mr-1" /> Resolve & Activate
            </Button>
          ) : undefined,
        },
        {
          label: "Generate First Month Invoice",
          description: "Create the first invoice after client is active (postpaid)",
          status: (state.clientActive && state.invoiceCreated) ? "done" : state.clientActive ? "active" : "pending",
          action: state.clientActive && !state.invoiceCreated ? (
            <Button size="sm" onClick={() => generatePostpaidInvoiceMutation.mutate()}
              isLoading={generatePostpaidInvoiceMutation.isPending}>
              <FileText className="h-3.5 w-3.5 mr-1" /> Generate Invoice
            </Button>
          ) : undefined,
        },
      ];

  const allDone = steps.every(s => s.status === "done");
  if (allDone) return null;

  return (
    <>
      <Card className="border-amber-200 bg-amber-50">
        <CardHeader>
          <div className="flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-amber-600" />
            <CardTitle className="text-amber-800 text-base">
              Activation Flow — {isPrepaid ? "Prepaid" : "Postpaid"}
            </CardTitle>
            <Badge variant="warning" className="ml-auto">{pendingSub?.plan?.name ?? "Pending"}</Badge>
          </div>
        </CardHeader>
        <CardContent>
          <ol className="space-y-3">
            {steps.map((step, i) => (
              <li key={i} className="flex items-start gap-3">
                <div className="mt-0.5 shrink-0">
                  {step.status === "done" ? (
                    <CheckCircle2 className="h-5 w-5 text-green-500" />
                  ) : step.status === "active" ? (
                    <div className="h-5 w-5 rounded-full border-2 border-amber-500 bg-amber-100 flex items-center justify-center">
                      <div className="h-2 w-2 rounded-full bg-amber-500" />
                    </div>
                  ) : (
                    <Circle className="h-5 w-5 text-gray-300" />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <p className={`text-sm font-medium ${
                    step.status === "done" ? "text-green-700 line-through opacity-60" :
                    step.status === "active" ? "text-gray-900" : "text-gray-400"
                  }`}>{step.label}</p>
                  {step.status !== "done" && (
                    <p className="text-xs text-gray-500 mt-0.5">{step.description}</p>
                  )}
                </div>
                {step.action && <div className="shrink-0">{step.action}</div>}
              </li>
            ))}
          </ol>
        </CardContent>
      </Card>

      {/* Pin Location Modal */}
      <Modal isOpen={showPinModal} onClose={() => setShowPinModal(false)} title="Pin Installation Location">
        <div className="space-y-4">
          <p className="text-sm text-gray-500">Enter the GPS coordinates for this installation site.</p>
          <Input label="Latitude" type="number" step="any" placeholder="e.g. 16.5325"
            value={pinForm.lat} onChange={e => setPinForm(f => ({ ...f, lat: e.target.value }))} />
          <Input label="Longitude" type="number" step="any" placeholder="e.g. 121.7710"
            value={pinForm.lng} onChange={e => setPinForm(f => ({ ...f, lng: e.target.value }))} />
          <p className="text-xs text-gray-400">💡 Tip: Get coordinates from Google Maps → right-click the location → copy lat/lng.</p>
          <div className="flex justify-end gap-2 pt-1">
            <Button variant="outline" onClick={() => setShowPinModal(false)}>Cancel</Button>
            <Button onClick={() => pinLocationMutation.mutate()} isLoading={pinLocationMutation.isPending}
              disabled={!pinForm.lat || !pinForm.lng}>
              <MapPin className="h-4 w-4 mr-1" /> Save Location
            </Button>
          </div>
        </div>
      </Modal>
    </>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function ClientDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const qc = useQueryClient();
  const [activeTab, setActiveTab] = useState<Tab>("profile");
  const [payInvoice, setPayInvoice] = useState<Invoice | null>(null);
  const [payForm, setPayForm] = useState({ amount: "", channel: "CASH", referenceNumber: "", notes: "" });

  const { data: client, isLoading, refetch: refetchClient } = useQuery<Client>({
    queryKey: ["client", id],
    queryFn: async () => { const r = await api.get<Client>(`/api/v1/clients/${id}`); return r.data; },
  });

  const { data: subscriptions = [] } = useQuery<Subscription[]>({
    queryKey: ["client-subscriptions", id],
    queryFn: async () => {
      const r = await api.get<{ data: Subscription[] }>(`/api/v1/clients/${id}/subscriptions`);
      return (r.data as any).data ?? [];
    },
  });

  const { data: allTickets = [] } = useQuery<TicketType[]>({
    queryKey: ["client-tickets-all", id],
    queryFn: async () => {
      const r = await api.get<LegacyPaginatedResponse<TicketType>>(`/api/v1/tickets?clientId=${id}&page=1&limit=50`);
      return (r.data as any).data ?? [];
    },
  });

  const { data: invoicesData, refetch: refetchInvoices } = useQuery<LegacyPaginatedResponse<Invoice>>({
    queryKey: ["client-invoices", id],
    queryFn: async () => {
      const r = await api.get<LegacyPaginatedResponse<Invoice>>(`/api/v1/invoices?clientId=${id}&page=1&limit=30`);
      return r.data;
    },
  });

  const { data: paymentsData } = useQuery<LegacyPaginatedResponse<Payment>>({
    queryKey: ["client-payments", id],
    queryFn: async () => {
      const r = await api.get<LegacyPaginatedResponse<Payment>>(`/api/v1/payments?clientId=${id}&page=1&limit=30`);
      return r.data;
    },
    enabled: activeTab === "payments",
  });

  const recordPayment = useMutation({
    mutationFn: async () => {
      await api.post("/api/v1/payments", {
        clientId: id, invoiceId: payInvoice?.id,
        amount: Number(payForm.amount), channel: payForm.channel,
        referenceNumber: payForm.referenceNumber || undefined,
        notes: payForm.notes || undefined,
        paymentDate: new Date().toISOString(),
      });
    },
    onSuccess: () => {
      toast.success("Payment recorded!");
      setPayInvoice(null);
      setPayForm({ amount: "", channel: "CASH", referenceNumber: "", notes: "" });
      qc.invalidateQueries({ queryKey: ["client-invoices", id] });
      qc.invalidateQueries({ queryKey: ["client-payments", id] });
      refetchInvoices();
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Payment failed"),
  });

  const tabs = [
    { key: "profile" as Tab, label: "Profile" },
    { key: "subscriptions" as Tab, label: "Subscriptions" },
    { key: "invoices" as Tab, label: "Invoices" },
    { key: "payments" as Tab, label: "Payments" },
    { key: "tickets" as Tab, label: "Tickets" },
  ];

  if (isLoading) return (
    <div className="space-y-4">
      <div className="h-8 w-48 animate-pulse bg-gray-200 rounded" />
      <Card><CardContent className="py-10"><div className="h-32 animate-pulse bg-gray-100 rounded-lg" /></CardContent></Card>
    </div>
  );

  if (!client) return (
    <div className="text-center py-20 text-gray-400">
      <p>Client not found</p>
      <Button variant="secondary" className="mt-4" onClick={() => router.push("/clients")}>Back to Clients</Button>
    </div>
  );

  const sub = client.subscriptions?.[0];
  const clientStatus = sub?.status ?? (client.isActive ? "ACTIVE" : "INACTIVE");
  const hasPendingSub = subscriptions.some(s => s.status === "PENDING");
  const needsActivation = !client.isActive || hasPendingSub;

  const handleRefresh = () => {
    refetchClient();
    qc.invalidateQueries({ queryKey: ["client-subscriptions", id] });
    qc.invalidateQueries({ queryKey: ["client-tickets-all", id] });
    qc.invalidateQueries({ queryKey: ["client-invoices", id] });
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="sm" onClick={() => router.push("/clients")}>
          <ArrowLeft className="h-4 w-4 mr-1" /> Back
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-gray-900">{client.firstName} {client.lastName}</h1>
          <p className="text-sm text-gray-500">{client.accountNumber} · {client.area?.name ?? "No area"}</p>
        </div>
        <Badge variant={statusColor[clientStatus] ?? "muted"}>{clientStatus}</Badge>
        <Button size="sm" variant="outline" onClick={handleRefresh}><RefreshCw className="h-4 w-4" /></Button>
      </div>

      {/* Activation Flow Banner — only when client is not yet active */}
      {needsActivation && (
        <ActivationFlowCard
          client={client}
          subscriptions={subscriptions}
          tickets={allTickets}
          invoices={invoicesData?.data ?? []}
          onRefresh={handleRefresh}
        />
      )}

      {/* Tabs */}
      <div className="flex border-b border-gray-200 overflow-x-auto">
        {tabs.map(tab => (
          <button key={tab.key} onClick={() => setActiveTab(tab.key)}
            className={`px-4 py-2.5 text-sm font-medium border-b-2 whitespace-nowrap transition-colors ${
              activeTab === tab.key ? "border-blue-600 text-blue-600" : "border-transparent text-gray-500 hover:text-gray-700"
            }`}>{tab.label}</button>
        ))}
      </div>

      {/* Profile */}
      {activeTab === "profile" && (
        <Card>
          <CardHeader><CardTitle>Client Profile</CardTitle></CardHeader>
          <CardContent>
            <dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                { label: "Account Number", value: client.accountNumber },
                { label: "Full Name", value: `${client.firstName} ${client.lastName}` },
                { label: "Email", value: client.email || "—" },
                { label: "Phone", value: client.phone },
                { label: "Address", value: client.address || "—" },
                { label: "Area", value: client.area?.name || "—" },
                { label: "Status", value: client.isActive ? "Active" : "Inactive" },
                { label: "Location", value: client.lat && client.lng ? `${client.lat}, ${client.lng}` : "Not pinned" },
                { label: "Joined", value: formatDate(client.createdAt) },
              ].map(({ label, value }) => (
                <div key={label}>
                  <dt className="text-xs font-medium text-gray-400 uppercase tracking-wide">{label}</dt>
                  <dd className="mt-0.5 text-sm text-gray-900">{value}</dd>
                </div>
              ))}
              <div>
                <dt className="text-xs font-medium text-gray-400 uppercase tracking-wide">Portal Access</dt>
                <dd className="mt-0.5 text-sm">
                  {client.portalAccessEnabled
                    ? <span className="text-green-600 font-medium">Enabled</span>
                    : <span className="text-gray-400">Disabled</span>
                  }
                </dd>
              </div>
            </dl>
          </CardContent>
        </Card>
      )}

      {/* Subscriptions */}
      {activeTab === "subscriptions" && (
        <Card>
          <CardHeader><CardTitle>Subscriptions</CardTitle></CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHead><TableRow><Th>Plan</Th><Th>Type</Th><Th>Status</Th><Th>Start Date</Th><Th>Monthly Rate</Th></TableRow></TableHead>
              <TableBody>
                {subscriptions.length === 0 ? <EmptyState message="No subscriptions" /> :
                  subscriptions.map(sub => (
                    <TableRow key={sub.id}>
                      <Td className="font-medium">{sub.plan?.name ?? "—"}</Td>
                      <Td><Badge variant="muted">{sub.type ?? sub.plan?.type ?? "—"}</Badge></Td>
                      <Td><Badge variant={statusColor[sub.status] ?? "muted"}>{sub.status}</Badge></Td>
                      <Td>{formatDate(sub.startDate)}</Td>
                      <Td>{formatCurrency(Number(sub.monthlyPrice ?? sub.plan?.monthlyPrice ?? 0))}</Td>
                    </TableRow>
                  ))
                }
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Invoices */}
      {activeTab === "invoices" && (
        <Card>
          <CardHeader><CardTitle>Invoices</CardTitle></CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHead><TableRow><Th>Invoice #</Th><Th>Total</Th><Th>Balance</Th><Th>Due Date</Th><Th>Status</Th><Th></Th></TableRow></TableHead>
              <TableBody>
                {!invoicesData?.data || invoicesData.data.length === 0 ? <EmptyState message="No invoices" /> :
                  invoicesData.data.map((inv: any) => (
                    <TableRow key={inv.id}>
                      <Td className="font-mono text-xs">{inv.invoiceNumber ?? inv.id.slice(0, 8)}</Td>
                      <Td>{formatCurrency(Number(inv.total ?? inv.amount ?? 0))}</Td>
                      <Td className={Number(inv.balance) > 0 ? "text-red-600 font-medium" : "text-gray-500"}>
                        {formatCurrency(Number(inv.balance ?? 0))}
                      </Td>
                      <Td>{inv.dueDate ? formatDate(inv.dueDate) : "—"}</Td>
                      <Td><Badge variant={invColor[inv.status] ?? "muted"}>{inv.status}</Badge></Td>
                      <Td>
                        {["SENT", "PARTIAL", "OVERDUE"].includes(inv.status) && (
                          <Button size="sm" onClick={() => {
                            setPayInvoice(inv);
                            setPayForm(f => ({ ...f, amount: String(Number(inv.balance ?? inv.total ?? 0)) }));
                          }}>Pay</Button>
                        )}
                      </Td>
                    </TableRow>
                  ))
                }
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Payments */}
      {activeTab === "payments" && (
        <Card>
          <CardHeader><CardTitle>Payment History</CardTitle></CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHead><TableRow><Th>Date</Th><Th>Amount</Th><Th>Channel</Th><Th>Reference</Th><Th>Notes</Th></TableRow></TableHead>
              <TableBody>
                {!paymentsData?.data || paymentsData.data.length === 0 ? <EmptyState message="No payments yet" /> :
                  paymentsData.data.map((p: any) => (
                    <TableRow key={p.id}>
                      <Td className="text-sm">{p.paymentDate ? formatDate(p.paymentDate) : formatDate(p.createdAt)}</Td>
                      <Td className="font-medium text-green-700">{formatCurrency(Number(p.amount))}</Td>
                      <Td><span className={`px-2 py-0.5 rounded-full text-xs font-medium ${channelColors[p.channel] ?? "bg-gray-100 text-gray-600"}`}>{p.channel}</span></Td>
                      <Td className="text-xs text-gray-500">{p.referenceNumber ?? p.orNumber ?? "—"}</Td>
                      <Td className="text-xs text-gray-500">{p.notes ?? "—"}</Td>
                    </TableRow>
                  ))
                }
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Tickets */}
      {activeTab === "tickets" && (
        <Card>
          <CardHeader><CardTitle>Tickets</CardTitle></CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHead><TableRow><Th>Subject</Th><Th>Type</Th><Th>Priority</Th><Th>Status</Th><Th>Created</Th></TableRow></TableHead>
              <TableBody>
                {allTickets.length === 0 ? <EmptyState message="No tickets" /> :
                  allTickets.map(t => (
                    <TableRow key={t.id}>
                      <Td className="font-medium">{t.subject}</Td>
                      <Td><Badge variant="muted">{t.type}</Badge></Td>
                      <Td><Badge variant={t.priority === "HIGH" ? "warning" : "muted"}>{t.priority}</Badge></Td>
                      <Td><Badge variant={t.status === "RESOLVED" ? "success" : t.status === "OPEN" ? "warning" : "muted"}>{t.status}</Badge></Td>
                      <Td className="text-xs text-gray-400">{formatDate(t.createdAt)}</Td>
                    </TableRow>
                  ))
                }
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Pay Invoice Modal */}
      <Modal isOpen={!!payInvoice} onClose={() => setPayInvoice(null)} title={`Record Payment — ${payInvoice?.invoiceNumber ?? ""}`}>
        {payInvoice && (
          <div className="space-y-4">
            <div className="bg-gray-50 rounded-lg p-3 text-sm space-y-1">
              <div className="flex justify-between"><span className="text-gray-500">Invoice Total</span><span className="font-medium">{formatCurrency(Number((payInvoice as any).total ?? payInvoice.amount))}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Amount Paid</span><span>{formatCurrency(Number((payInvoice as any).amountPaid ?? 0))}</span></div>
              <div className="flex justify-between font-medium text-red-600"><span>Balance Due</span><span>{formatCurrency(Number((payInvoice as any).balance ?? payInvoice.amount))}</span></div>
            </div>
            <Input label="Amount" type="number" value={payForm.amount} onChange={e => setPayForm(f => ({ ...f, amount: e.target.value }))} />
            <div className="flex flex-col gap-1.5">
              <label className="text-sm font-medium text-gray-700">Payment Method</label>
              <select className="border rounded-lg px-3 py-2 text-sm" value={payForm.channel} onChange={e => setPayForm(f => ({ ...f, channel: e.target.value }))}>
                {["CASH","GCASH","MAYA","BANK_TRANSFER","CHECK"].map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <Input label="Reference # (optional)" value={payForm.referenceNumber} onChange={e => setPayForm(f => ({ ...f, referenceNumber: e.target.value }))} />
            <Input label="Notes (optional)" value={payForm.notes} onChange={e => setPayForm(f => ({ ...f, notes: e.target.value }))} />
            <div className="flex justify-end gap-2 pt-1">
              <Button variant="outline" onClick={() => setPayInvoice(null)}>Cancel</Button>
              <Button onClick={() => recordPayment.mutate()} isLoading={recordPayment.isPending} disabled={!payForm.amount}>Record Payment</Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
