"use client";

import { useEffect, useState } from "react";
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 { CategoryModal, ConfirmDialog, TableSkeleton } from "@/components/shared";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import type { AdPlacement } from "@/lib/types";

export default function AdZonesPage() {
  const [placements, setPlacements] = useState<AdPlacement[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editTarget, setEditTarget] = useState<AdPlacement | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<AdPlacement | null>(null);
  const [page, setPage] = useState(1);
  const perPage = 10;

  const fetchPlacements = async () => {
    try {
      const { data } = await api.get("/api/advertising/placements");
      setPlacements(data.data);
    } catch {
      toast.error("Failed to load ad zones");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPlacements();
  }, []);

  const handleSubmit = async (formData: { name: string; description: string }) => {
    try {
      if (editTarget) {
        await api.put(`/api/advertising/placements/${editTarget.id}`, formData);
        toast.success("Zone updated");
      } else {
        await api.post("/api/advertising/placements", formData);
        toast.success("Zone created");
      }
      setEditTarget(null);
      fetchPlacements();
    } catch {
      toast.error("Failed to save zone");
      throw new Error("Failed");
    }
  };

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

  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">Ad Zones</h1>
          <p className="text-sm text-muted-foreground">Manage advertising placement zones</p>
        </div>
        <Button onClick={() => { setEditTarget(null); setModalOpen(true); }}>
          <Plus className="mr-2 h-4 w-4" /> Add Zone
        </Button>
      </div>

      <Card>
        <CardContent className="p-4">
          {loading ? (
            <TableSkeleton columns={4} rows={5} />
          ) : (
            <div className="overflow-x-auto rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Zone Name</TableHead>
                    <TableHead className="hidden sm:table-cell">Description</TableHead>
                    <TableHead>Active Ads</TableHead>
                    <TableHead className="w-[100px]">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {placements.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={4} className="py-8 text-center text-muted-foreground">
                        No ad zones found
                      </TableCell>
                    </TableRow>
                  )}
                  {placements.slice((page - 1) * perPage, page * perPage).map((placement) => (
                    <TableRow key={placement.id}>
                      <TableCell className="font-medium">{placement.name}</TableCell>
                      <TableCell className="hidden sm:table-cell text-muted-foreground">
                        {placement.description || "—"}
                      </TableCell>
                      <TableCell>{placement.advertisements_count ?? 0}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0"
                            onClick={() => { setEditTarget(placement); setModalOpen(true); }}
                          >
                            <Pencil className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                            onClick={() => setDeleteTarget(placement)}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
          {!loading && placements.length > perPage && (
            <div className="mt-4 flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                Page {page} of {Math.ceil(placements.length / perPage)} ({placements.length} zones)
              </p>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
                  Previous
                </Button>
                <Button variant="outline" size="sm" disabled={page >= Math.ceil(placements.length / perPage)} onClick={() => setPage((p) => p + 1)}>
                  Next
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <CategoryModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        onSubmit={handleSubmit}
        initialData={editTarget ? { name: editTarget.name, description: editTarget.description || "" } : null}
        title={editTarget ? "Edit Ad Zone" : "Add Ad Zone"}
      />

      <ConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
        onConfirm={handleDelete}
        title="Delete Ad Zone"
        description={`Delete "${deleteTarget?.name}"? Ads in this zone will be affected.`}
      />
    </div>
  );
}
