"use client";

import { useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { SearchInput, DataPagination, StatusBadge, TableSkeleton } from "@/components/shared";
import { useDataTable } from "@/hooks/use-data-table";
import { toast } from "sonner";
import api from "@/lib/api";
import type { Subscription, PaginatedResponse } from "@/lib/types";

export default function MagazineSubscriptionsPage() {
  const { page, search, setPage, setSearch } = useDataTable();
  const [data, setData] = useState<PaginatedResponse<Subscription> | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchSubscriptions = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      params.set("page", String(page));
      params.set("per_page", "15");
      const { data: res } = await api.get(`/api/magazine/subscriptions?${params}`);
      setData(res);
    } catch {
      toast.error("Failed to load subscriptions");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSubscriptions();
  }, [page, search]);

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-display text-2xl font-semibold">Subscriptions</h1>
          <p className="text-sm text-muted-foreground">Manage magazine subscriptions</p>
        </div>
      </div>

      <Card>
        <CardContent className="p-4">
          <div className="mb-4">
            <SearchInput value={search} onChange={setSearch} placeholder="Search by name or email..." className="max-w-sm" />
          </div>

          {loading ? (
            <TableSkeleton columns={6} rows={5} />
          ) : (
            <>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>User</TableHead>
                      <TableHead>Plan</TableHead>
                      <TableHead className="hidden sm:table-cell">Amount</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="hidden md:table-cell">Starts</TableHead>
                      <TableHead className="hidden md:table-cell">Ends</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data?.data.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} className="py-8 text-center text-muted-foreground">
                          No subscriptions found
                        </TableCell>
                      </TableRow>
                    )}
                    {data?.data.map((sub) => (
                      <TableRow key={sub.id}>
                        <TableCell>
                          <div>
                            <p className="font-medium">{sub.user?.name ?? "—"}</p>
                            <p className="text-xs text-muted-foreground">{sub.user?.email}</p>
                          </div>
                        </TableCell>
                        <TableCell className="capitalize">{sub.plan}</TableCell>
                        <TableCell className="hidden sm:table-cell">
                          {sub.currency} {sub.amount_paid}
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={sub.status} />
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {new Date(sub.starts_at).toLocaleDateString()}
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {sub.ends_at ? new Date(sub.ends_at).toLocaleDateString() : "—"}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {data && (
                <div className="mt-4">
                  <DataPagination
                    currentPage={data.meta.current_page}
                    lastPage={data.meta.last_page}
                    onPageChange={setPage}
                    total={data.meta.total}
                    from={data.meta.from}
                    to={data.meta.to}
                  />
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
