import {notFound, redirect} from "next/navigation";
import Link from "next/link";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Button} from "@/components/ui/button";
import {ArrowLeft, User, Calendar} from "lucide-react";
import {CustomerActions} from "./customer-actions";

type CustomerDetailPageProps = {
  params: Promise<{tenantSlug: string; customerId: string; locale: string}>;
};

export default async function CustomerDetailPage({params}: CustomerDetailPageProps) {
  const {tenantSlug, customerId, locale} = await params;
  const session = await auth();
  if (!session?.user?.id) redirect(`/${locale}/auth/sign-in`);

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

  const db = getTenantDb(tenant.id);
  const profile = await db.customerProfile.findFirst({
    where: {id: customerId},
    include: {
      user: true,
      bookings: {
        include: {vehicle: {include: {brand: true}}},
        orderBy: {createdAt: "desc"},
        take: 10
      }
    }
  });

  if (!profile) notFound();

  const customerName = profile.user.firstName
    ? `${profile.user.firstName} ${profile.user.lastName ?? ""}`
    : profile.user.email;

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

  return (
    <div className="max-w-3xl space-y-6">
      <div className="flex items-center gap-3">
        <Link href={`/company/${tenantSlug}/customers`}>
          <Button variant="ghost" size="sm">
            <ArrowLeft className="mr-1 h-4 w-4" />
            Customers
          </Button>
        </Link>
        <div>
          <h1 className="text-xl font-bold text-slate-900">{customerName}</h1>
          <p className="text-sm text-slate-500">{profile.user.email}</p>
        </div>
        {profile.blacklisted && (
          <span className="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">Blacklisted</span>
        )}
      </div>

      <Card>
        <CardHeader><CardTitle className="flex items-center gap-2"><User className="h-4 w-4 text-blue-600" />Personal Information</CardTitle></CardHeader>
        <CardContent>
          <div className="grid gap-3 sm:grid-cols-2 text-sm">
            {[
              {label: "Full Name", value: customerName},
              {label: "Email", value: profile.user.email},
              {label: "Phone", value: profile.user.phone ?? "—"},
              {label: "License #", value: profile.driverLicenseNumber ?? "—"},
              {label: "Customer Code", value: profile.customerCode ?? "—"},
              {label: "Member Since", value: new Date(profile.createdAt).toLocaleDateString()}
            ].map(({label, value}) => (
              <div key={label} className="rounded-xl bg-slate-50 p-3">
                <p className="text-xs text-slate-500">{label}</p>
                <p className="mt-0.5 font-medium text-slate-900">{value}</p>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <CustomerActions
        customerId={customerId}
        tenantSlug={tenantSlug}
        isBlacklisted={profile.blacklisted}
      />

      <Card>
        <CardHeader><CardTitle className="flex items-center gap-2"><Calendar className="h-4 w-4 text-blue-600" />Booking History</CardTitle></CardHeader>
        <CardContent>
          {profile.bookings.length === 0 ? (
            <p className="py-4 text-center text-sm text-slate-400">No bookings</p>
          ) : (
            <div className="space-y-2">
              {profile.bookings.map((b) => (
                <Link key={b.id} href={`/company/${tenantSlug}/bookings/${b.id}`}>
                  <div className="flex items-center justify-between rounded-xl border border-slate-100 p-3 transition hover:bg-slate-50 text-sm">
                    <div>
                      <p className="font-mono text-xs text-blue-600">{b.bookingNumber}</p>
                      <p className="text-slate-600">{b.vehicle.brand.name} {b.vehicle.name}</p>
                      <p className="text-xs text-slate-400">{new Date(b.pickupAt).toLocaleDateString()} → {new Date(b.dropoffAt).toLocaleDateString()}</p>
                    </div>
                    <div className="text-end">
                      <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${statusColors[b.status] ?? "bg-slate-100 text-slate-600"}`}>
                        {b.status.replace(/_/g, " ")}
                      </span>
                      <p className="mt-1 text-sm font-semibold text-slate-900">${Number(b.totalAmount).toFixed(0)}</p>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
