"use client";

import { useQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { RefreshCw, Wifi, AlertCircle } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { formatDate, formatCurrency } from "@/lib/utils";
import api from "@/lib/api";
import type { PaginatedResponse } from "@/types";

interface Subscription {
  id: string;
  clientId: string;
  status: string;
  startDate: string;
  endDate?: string;
  client?: { firstName: string; lastName: string; accountNumber: string };
  plan?: { name: string; type: string; monthlyPrice: number };
  planId?: string;
  monthlyRate?: number;
  mrc?: number;
  type?: string;
}

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

export default function SubscriptionsPage() {
  const router = useRouter();

  const { data, isLoading, isError, error, refetch, isFetching } = useQuery<PaginatedResponse<Subscription>>({
    queryKey: ["subscriptions"],
    queryFn: async () => {
      const res = await api.get<PaginatedResponse<Subscription>>("/api/v1/subscriptions?page=1&limit=50");
      return res.data;
    },
    retry: false,
  });

  const subscriptions = data?.data ?? [];
  const meta = data?.meta;

  const isNotFound =
    isError &&
    (error as { response?: { status?: number } })?.response?.status === 404;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Subscriptions</h1>
          <p className="text-sm text-gray-500">{meta?.total ?? 0} total subscriptions</p>
        </div>
        <Button size="sm" variant="outline" onClick={() => refetch()} disabled={isFetching}>
          <RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} />
          {isFetching ? "Checking…" : "Retry"}
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>All Subscriptions</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="p-6 space-y-3">
              {Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="h-10 animate-pulse bg-gray-100 rounded-lg" />
              ))}
            </div>
          ) : isNotFound || (isError && !data) ? (
            <div className="flex flex-col items-center justify-center py-16 text-center px-6">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-blue-50 mb-4">
                <Wifi className="h-8 w-8 text-blue-400" />
              </div>
              <h3 className="text-base font-semibold text-gray-700 mb-2">Subscriptions Module Not Yet Available</h3>
              <p className="text-sm text-gray-500 max-w-sm mb-4">
                Subscription data will appear here once the module is deployed.
              </p>
              <div className="flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 px-3 py-1.5 rounded-full mb-5">
                <AlertCircle className="h-3.5 w-3.5" />
                <span>API endpoint not yet available</span>
              </div>
              <Button variant="secondary" onClick={() => refetch()} disabled={isFetching}>
                <RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} />
                {isFetching ? "Checking…" : "Retry Now"}
              </Button>
            </div>
          ) : subscriptions.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center px-6">
              <div className="flex h-14 w-14 items-center justify-center rounded-full bg-gray-100 mb-3">
                <Wifi className="h-7 w-7 text-gray-400" />
              </div>
              <p className="text-sm text-gray-500">No subscriptions yet.</p>
              <Button variant="secondary" size="sm" className="mt-3" onClick={() => refetch()}>
                <RefreshCw className="h-4 w-4" /> Refresh
              </Button>
            </div>
          ) : (
            <Table>
              <TableHead>
                <TableRow>
                  <Th>Client</Th>
                  <Th>Plan</Th>
                  <Th>Type</Th>
                  <Th>Status</Th>
                  <Th>Start Date</Th>
                  <Th>MRC</Th>
                </TableRow>
              </TableHead>
              <TableBody>
                {subscriptions.map((sub) => (
                  <TableRow
                    key={sub.id}
                    className="hover:bg-gray-50 transition-colors cursor-pointer"
                    onClick={() => sub.clientId && router.push(`/clients/${sub.clientId}`)}
                  >
                    <Td>
                      {sub.client ? (
                        <div>
                          <p className="font-medium text-sm">{sub.client.firstName} {sub.client.lastName}</p>
                          <p className="text-xs text-gray-400 font-mono">{sub.client.accountNumber}</p>
                        </div>
                      ) : (
                        <span className="text-gray-400 text-sm">—</span>
                      )}
                    </Td>
                    <Td className="font-medium">{sub.plan?.name ?? sub.planId ?? "—"}</Td>
                    <Td><Badge variant="muted">{sub.plan?.type ?? sub.type ?? "—"}</Badge></Td>
                    <Td>
                      <Badge variant={statusVariant[sub.status] ?? "muted"}>{sub.status}</Badge>
                    </Td>
                    <Td>{formatDate(sub.startDate)}</Td>
                    <Td>{formatCurrency(sub.plan?.monthlyPrice ?? sub.monthlyRate ?? sub.mrc ?? 0)}</Td>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
