"use client";

import { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { AlertCircle } from "lucide-react";
import LoanActions from "@/components/web/admin/LoanActions";

export type LoanWithRelations = {
  id: string;
  borrowedAt: Date;
  dueDate: Date;
  status: "ACTIVE" | "RETURNED" | "OVERDUE";
  pickupConfirmed: boolean;
  returnConfirmed: boolean;
  physicalCopyId?: string | null;

  physicalCopy?: {
    copyCode: string | null;
  } | null;

  user: {
    id: string;
    name: string | null;
    email: string;
    studentId: string | null;
  };

  book: {
    title: string;
    author: string;
  };
};

export const columns: ColumnDef<LoanWithRelations>[] = [
  {
    accessorKey: "student",
    header: "Student",
    cell: ({ row }) => {
      const user = row.original.user;
      return (
        <div className="space-y-1">
          <p className="font-medium">{user.name || "—"}</p>
          <p className="text-xs text-muted-foreground">
            {user.studentId || user.email}
          </p>
        </div>
      );
    },
  },
  {
    accessorKey: "book",
    header: "Book",
    filterFn: (row, _columnId, filterValue: string) => {
      const book = row.original.book
      const q = filterValue.toLowerCase()
      return (
        book.title.toLowerCase().includes(q) ||
        book.author.toLowerCase().includes(q)
      )
    },
    cell: ({ row }) => {
      const book = row.original.book;
      return (
        <div className="space-y-1">
          <p className="font-medium line-clamp-1">{book.title}</p>
          <p className="text-xs text-muted-foreground">{book.author}</p>
        </div>
      );
    },
  },
  {
    id: "copy",
    header: "Type / Copy",
    cell: ({ row }) => {
      const physicalCopy = row.original.physicalCopy;
      const isPhysical = !!row.original.physicalCopyId || !!physicalCopy;

      return (
        <div className="text-sm">
          {isPhysical ? (
            <span className="font-mono text-amber-600">
              {physicalCopy?.copyCode || "Physical"}
            </span>
          ) : (
            <span className="text-emerald-600 font-medium">Digital</span>
          )}
        </div>
      );
    },
  },
  {
    accessorKey: "borrowedAt",
    header: "Borrowed",
    cell: ({ row }) => (
      <span className="text-muted-foreground">
        {new Date(row.original.borrowedAt).toLocaleDateString()}
      </span>
    ),
  },
  {
    accessorKey: "dueDate",
    header: "Due Date",
    cell: ({ row }) => {
      const dueDate = new Date(row.original.dueDate);
      const isOverdue =
        dueDate < new Date() && row.original.status === "ACTIVE";

      return (
        <div className={`flex items-center gap-1.5 ${isOverdue ? "text-red-600 font-medium" : ""}`}>
          {isOverdue && <AlertCircle className="h-4 w-4" />}
          {dueDate.toLocaleDateString()}
        </div>
      );
    },
  },
  {
    accessorKey: "status",
    header: "Status",
    cell: ({ row }) => {
      const isOverdue =
        new Date(row.original.dueDate) < new Date() &&
        row.original.status === "ACTIVE";

      const displayStatus = isOverdue ? "Overdue" : row.original.status;

      return (
        <Badge
          variant="outline"
          className={
            row.original.status === "RETURNED"
              ? "bg-green-100 text-green-700 border-green-200"
              : isOverdue
              ? "bg-red-100 text-red-700 border-red-200"
              : "bg-blue-100 text-blue-700 border-blue-200"
          }
        >
          {displayStatus}
        </Badge>
      );
    },
  },
  {
    id: "actions",
    header: "Actions",
    cell: ({ row }) => {
      const loan = row.original;
      return (
        <LoanActions
          loanId={loan.id}
          status={loan.status}
          pickupConfirmed={loan.pickupConfirmed}
          returnConfirmed={loan.returnConfirmed}
          isPhysical={!!loan.physicalCopyId}
        />
      );
    },
  },
];