import Link from "next/link";
import {notFound} from "next/navigation";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Badge} from "@/components/ui/badge";
import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {FileSignature, Plus, Search, Calendar, Clock} from "lucide-react";

type ContractsPageProps = {
  params: Promise<{tenantSlug: string}>;
  searchParams: Promise<{status?: string; q?: string}>;
};

const statusColors: Record<string, string> = {
  ACTIVE: "bg-green-100 text-green-700",
  COMPLETED: "bg-slate-100 text-slate-600",
  OVERDUE: "bg-red-100 text-red-700",
  CANCELLED: "bg-orange-100 text-orange-700",
  DRAFT: "bg-yellow-100 text-yellow-700"
};

export default async function ContractsPage({params, searchParams}: ContractsPageProps) {
  const {tenantSlug} = await params;
  const {status, q} = await searchParams;

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) notFound();

  const db = getTenantDb(tenant.id);

  const contracts = await db.rentalContract.findMany({
    where: {
      ...(status ? {status: status as never} : {}),
      ...(q ? {
        OR: [
          {contractNumber: {contains: q, mode: "insensitive"}},
          {customerName: {contains: q, mode: "insensitive"}},
          {vehiclePlate: {contains: q, mode: "insensitive"}}
        ]
      } : {})
    },
    include: {booking: {select: {bookingNumber: true}}},
    orderBy: {createdAt: "desc"},
    take: 50
  });

  // Count by status
  const counts = await db.rentalContract.groupBy({
    by: ["status"],
    _count: {_all: true}
  });
  const countMap = Object.fromEntries(counts.map((c) => [c.status, c._count._all]));

  const now = new Date();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Contracts</h1>
          <p className="mt-1 text-slate-500">Manage rental contracts for {tenant.name}</p>
        </div>
        <Link href={`/company/${tenantSlug}/contracts/new`}>
          <Button className="bg-blue-600 hover:bg-blue-700">
            <Plus className="mr-2 h-4 w-4" />
            New Contract
          </Button>
        </Link>
      </div>

      {/* Status Filter Tabs */}
      <div className="flex flex-wrap gap-2">
        {[
          {key: "", label: "All", count: Object.values(countMap).reduce((a, b) => a + b, 0)},
          {key: "ACTIVE", label: "Active", count: countMap["ACTIVE"] ?? 0},
          {key: "OVERDUE", label: "Overdue", count: countMap["OVERDUE"] ?? 0},
          {key: "COMPLETED", label: "Completed", count: countMap["COMPLETED"] ?? 0},
          {key: "CANCELLED", label: "Cancelled", count: countMap["CANCELLED"] ?? 0}
        ].map(({key, label, count}) => (
          <Link key={key} href={`?status=${key}`}>
            <Button
              variant={status === key || (!status && key === "") ? "default" : "outline"}
              size="sm"
              className={status === key || (!status && key === "") ? "bg-blue-600 hover:bg-blue-700" : ""}
            >
              {label}
              {count > 0 && (
                <span className="ml-1.5 rounded-full bg-white/20 px-1.5 py-0.5 text-xs">{count}</span>
              )}
            </Button>
          </Link>
        ))}
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 sm:grid-cols-4">
        {[
          {label: "Active", value: countMap["ACTIVE"] ?? 0, color: "text-green-600 bg-green-50", icon: FileSignature},
          {label: "Overdue", value: countMap["OVERDUE"] ?? 0, color: "text-red-600 bg-red-50", icon: Clock},
          {label: "Completed", value: countMap["COMPLETED"] ?? 0, color: "text-slate-600 bg-slate-50", icon: Calendar},
          {label: "Total", value: Object.values(countMap).reduce((a, b) => a + b, 0), color: "text-blue-600 bg-blue-50", icon: FileSignature}
        ].map(({label, value, color, icon: Icon}) => (
          <Card key={label}>
            <CardContent className="flex items-center gap-3 p-4">
              <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${color}`}>
                <Icon className="h-5 w-5" />
              </div>
              <div>
                <p className="text-xl font-bold text-slate-900">{value}</p>
                <p className="text-xs text-slate-500">{label}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Contracts Table */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileSignature className="h-5 w-5 text-blue-600" />
            Rental Contracts
          </CardTitle>
        </CardHeader>
        <CardContent>
          {contracts.length === 0 ? (
            <div className="py-12 text-center">
              <FileSignature className="mx-auto mb-3 h-10 w-10 text-slate-300" />
              <p className="text-slate-500">No contracts found</p>
              <Link href={`/company/${tenantSlug}/contracts/new`} className="mt-3 inline-block">
                <Button size="sm">Create First Contract</Button>
              </Link>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-100">
                    <th className="py-3 pe-4 text-start font-semibold text-slate-600">Contract #</th>
                    <th className="py-3 pe-4 text-start font-semibold text-slate-600">Customer</th>
                    <th className="py-3 pe-4 text-start font-semibold text-slate-600">Vehicle</th>
                    <th className="py-3 pe-4 text-start font-semibold text-slate-600">Period</th>
                    <th className="py-3 pe-4 text-start font-semibold text-slate-600">Days Left</th>
                    <th className="py-3 pe-4 text-start font-semibold text-slate-600">Status</th>
                    <th className="py-3 text-end font-semibold text-slate-600">Amount</th>
                  </tr>
                </thead>
                <tbody>
                  {contracts.map((contract) => {
                    const daysLeft = Math.ceil((new Date(contract.dropoffDate).getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
                    const isOverdue = daysLeft < 0 && contract.status === "ACTIVE";
                    return (
                      <tr key={contract.id} className="border-b border-slate-50 hover:bg-slate-50">
                        <td className="py-3 pe-4">
                          <Link href={`/company/${tenantSlug}/contracts/${contract.id}`} className="font-mono text-xs text-blue-600 hover:underline">
                            {contract.contractNumber}
                          </Link>
                          <p className="text-xs text-slate-400">{contract.booking.bookingNumber}</p>
                        </td>
                        <td className="py-3 pe-4">
                          <p className="font-medium text-slate-900">{contract.customerName}</p>
                          <p className="text-xs text-slate-500">{contract.customerPhone}</p>
                        </td>
                        <td className="py-3 pe-4 text-slate-700">
                          <p>{contract.vehicleName}</p>
                          <p className="font-mono text-xs text-slate-400">{contract.vehiclePlate}</p>
                        </td>
                        <td className="py-3 pe-4 text-slate-600">
                          <p className="text-xs">{new Date(contract.pickupDate).toLocaleDateString()}</p>
                          <p className="text-xs text-slate-400">→ {new Date(contract.dropoffDate).toLocaleDateString()}</p>
                        </td>
                        <td className="py-3 pe-4">
                          {contract.status === "ACTIVE" && (
                            <span className={`font-semibold text-sm ${isOverdue ? "text-red-600" : daysLeft <= 2 ? "text-orange-600" : "text-green-600"}`}>
                              {isOverdue ? `${Math.abs(daysLeft)}d overdue` : `${daysLeft}d left`}
                            </span>
                          )}
                          {contract.status !== "ACTIVE" && <span className="text-slate-400 text-xs">—</span>}
                        </td>
                        <td className="py-3 pe-4">
                          <Badge className={statusColors[contract.status] ?? "bg-slate-100"}>
                            {contract.status}
                          </Badge>
                        </td>
                        <td className="py-3 text-end font-semibold text-slate-900">
                          {tenant.currency} {Number(contract.totalAmount).toFixed(0)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
