"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { SearchInput, DataPagination, StatusBadge, ConfirmDialog, TableSkeleton } from "@/components/shared";
import { useDataTable } from "@/hooks/use-data-table";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import type { Advertisement, PaginatedResponse } from "@/lib/types";

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

  const fetchAds = 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/advertising/advertisements?${params}`);
      setData(res);
    } catch {
      toast.error("Failed to load ads");
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/api/advertising/advertisements/${deleteTarget.id}`);
      toast.success("Ad deleted");
      fetchAds();
    } catch {
      toast.error("Failed to delete ad");
    }
  };

  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">Advertisements</h1>
          <p className="text-sm text-muted-foreground">Manage advertising campaigns</p>
        </div>
        <Button asChild>
          <Link href="/dashboard/advertising/ads/create">
            <Plus className="mr-2 h-4 w-4" /> New Ad
          </Link>
        </Button>
      </div>

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

          {loading ? (
            <TableSkeleton columns={6} rows={5} />
          ) : (
            <>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Ad</TableHead>
                      <TableHead className="hidden sm:table-cell">Zone</TableHead>
                      <TableHead className="hidden md:table-cell">Impressions</TableHead>
                      <TableHead className="hidden md:table-cell">Clicks</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="w-[100px]">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data?.data.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} className="py-8 text-center text-muted-foreground">
                          No ads found
                        </TableCell>
                      </TableRow>
                    )}
                    {data?.data.map((ad) => (
                      <TableRow key={ad.id}>
                        <TableCell>
                          <div>
                            <p className="font-medium line-clamp-1">{ad.title}</p>
                            <p className="text-xs text-muted-foreground">{ad.advertiser_name}</p>
                          </div>
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">
                          {ad.placement?.name || "—"}
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {(ad.impressions_count || 0).toLocaleString()}
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {(ad.clicks_count || 0).toLocaleString()}
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={ad.status} />
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Button variant="ghost" size="sm" asChild className="h-8 w-8 p-0">
                              <Link href={`/dashboard/advertising/ads/edit/${ad.id}`}>
                                <Pencil className="h-3.5 w-3.5" />
                              </Link>
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                              onClick={() => setDeleteTarget(ad)}
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        </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>

      <ConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
        onConfirm={handleDelete}
        title="Delete Advertisement"
        description={`Delete "${deleteTarget?.title}"? This cannot be undone.`}
      />
    </div>
  );
}
