"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, FileText } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import type { MagazineIssue, PaginatedResponse } from "@/lib/types";

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

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

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

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/api/magazine/issues/${deleteTarget.id}`);
      toast.success("Issue deleted");
      fetchIssues();
    } catch {
      toast.error("Failed to delete issue");
    }
  };

  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">Magazine Issues</h1>
          <p className="text-sm text-muted-foreground">Manage magazine issues</p>
        </div>
        <Button asChild>
          <Link href="/dashboard/magazine/issues/create">
            <Plus className="mr-2 h-4 w-4" /> New Issue
          </Link>
        </Button>
      </div>

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

          {loading ? (
            <TableSkeleton columns={5} rows={5} />
          ) : (
            <>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Issue</TableHead>
                      <TableHead className="hidden sm:table-cell">Volume/Number</TableHead>
                      <TableHead className="hidden md:table-cell">Published</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="hidden sm:table-cell">Articles</TableHead>
                      <TableHead className="hidden md:table-cell">PDF</TableHead>
                      <TableHead className="w-[120px]">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data?.data.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={7} className="py-8 text-center text-muted-foreground">
                          No issues found
                        </TableCell>
                      </TableRow>
                    )}
                    {data?.data.map((issue) => (
                      <TableRow key={issue.id}>
                        <TableCell>
                          <div className="flex items-center gap-3">
                            {issue.cover_thumbnail ? (
                              <img src={issue.cover_thumbnail} alt={issue.title} className="h-12 w-9 rounded object-cover" />
                            ) : (
                              <div className="flex h-12 w-9 items-center justify-center rounded bg-muted text-[10px] text-muted-foreground">
                                N/A
                              </div>
                            )}
                            <p className="font-medium line-clamp-1">{issue.title}</p>
                          </div>
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">
                          Vol. {issue.volume_number}, No. {issue.issue_number}
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {issue.published_at ? new Date(issue.published_at).toLocaleDateString() : "—"}
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={issue.status} />
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">
                          {issue.articles_count ?? 0}
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {issue.has_pdf ? (
                            <span className="inline-flex items-center gap-1 text-xs text-green-600">
                              <FileText className="h-3 w-3" /> Uploaded
                            </span>
                          ) : (
                            <span className="text-xs text-muted-foreground">—</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            {issue.has_pdf && (
                              <Button variant="ghost" size="sm" asChild className="h-8 w-8 p-0" title="Read PDF">
                                <Link href={`/dashboard/magazine/issues/${issue.id}/read`}>
                                  <FileText className="h-3.5 w-3.5" />
                                </Link>
                              </Button>
                            )}
                            <Button variant="ghost" size="sm" asChild className="h-8 w-8 p-0">
                              <Link href={`/dashboard/magazine/issues/${issue.id}/edit`}>
                                <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(issue)}
                            >
                              <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 Issue"
        description={`Delete "${deleteTarget?.title}"? All articles in this issue will also be affected.`}
      />
    </div>
  );
}
