import {notFound} from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import {getTranslations} from "next-intl/server";
import {prisma} from "@/lib/db/prisma";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Badge} from "@/components/ui/badge";
import {Button} from "@/components/ui/button";
import {Building2, MapPin, Phone, Mail, Globe, Car, GitBranch} from "lucide-react";

type CompanyDetailsPageProps = {
  params: Promise<{slug: string}>;
};

export async function generateMetadata({params}: CompanyDetailsPageProps) {
  const {slug} = await params;
  const tenant = await prisma.tenant.findUnique({where: {slug}});
  return {title: tenant ? `${tenant.name} - Car Rental` : "Company Not Found"};
}

export default async function CompanyDetailsPage({params}: CompanyDetailsPageProps) {
  const {slug} = await params;
  const t = await getTranslations("companies");

  const company = await prisma.tenant.findUnique({
    where: {slug, status: "ACTIVE"},
    include: {
      branches: {where: {isActive: true}, orderBy: {name: "asc"}},
      vehicles: {
        where: {isPublic: true, status: "AVAILABLE"},
        include: {brand: true, model: true},
        orderBy: [{featured: "desc"}, {createdAt: "desc"}],
        take: 9
      }
    }
  });

  if (!company || !company.isPublicListingEnabled) notFound();

  const categoryLabel: Record<string, string> = {
    ECONOMY: "Economy", SEDAN: "Sedan", SUV: "SUV",
    LUXURY: "Luxury", SPORT: "Sport", VAN: "Van", PICKUP: "Pickup"
  };

  return (
    <div className="mx-auto max-w-7xl px-6 py-10">
      {/* Header */}
      <div className="mb-8 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
        <div className="h-32 bg-gradient-to-r from-blue-600 to-blue-800" />
        <div className="p-6">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-end">
            <div className="-mt-12 h-20 w-20 overflow-hidden rounded-xl border-4 border-white bg-white shadow-md shrink-0">
              {company.logoUrl ? (
                <Image src={company.logoUrl} alt={company.name} width={80} height={80} className="object-contain" unoptimized />
              ) : (
                <div className="flex h-full items-center justify-center bg-slate-50">
                  <Building2 className="h-8 w-8 text-slate-400" />
                </div>
              )}
            </div>
            <div className="flex-1">
              <h1 className="text-2xl font-bold text-slate-900">{company.name}</h1>
              <div className="mt-1 flex flex-wrap items-center gap-3 text-sm text-slate-500">
                {company.city && (
                  <span className="flex items-center gap-1"><MapPin className="h-4 w-4" />{company.city}</span>
                )}
                {company.email && (
                  <span className="flex items-center gap-1"><Mail className="h-4 w-4" />{company.email}</span>
                )}
                {company.phone && (
                  <span className="flex items-center gap-1"><Phone className="h-4 w-4" />{company.phone}</span>
                )}
              </div>
            </div>
            <div className="flex gap-3">
              {company.website && (
                <a href={company.website} target="_blank" rel="noopener noreferrer">
                  <Button variant="outline" size="sm">
                    <Globe className="mr-1.5 h-4 w-4" />
                    {t("details.visitWebsite")}
                  </Button>
                </a>
              )}
              <Link href="/contact">
                <Button size="sm">
                  <Phone className="mr-1.5 h-4 w-4" />
                  {t("details.contactUs")}
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className="grid gap-8 lg:grid-cols-3">
        {/* Fleet */}
        <div className="lg:col-span-2">
          <h2 className="mb-4 text-xl font-bold text-slate-900">{t("details.ourFleet")}</h2>
          {company.vehicles.length === 0 ? (
            <div className="rounded-2xl border border-dashed border-slate-300 py-16 text-center">
              <Car className="mx-auto h-10 w-10 text-slate-300" />
              <p className="mt-2 text-slate-500">No vehicles available</p>
            </div>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {company.vehicles.map((vehicle) => (
                <Link key={vehicle.id} href={`/cars/${vehicle.slug}`}>
                  <Card className="group overflow-hidden border-slate-200 transition hover:-translate-y-0.5 hover:shadow-md">
                    <div className="relative h-36 overflow-hidden bg-slate-100">
                      {vehicle.primaryImageUrl ? (
                        <Image src={vehicle.primaryImageUrl} alt={vehicle.name} fill className="object-cover transition group-hover:scale-105" unoptimized />
                      ) : (
                        <div className="flex h-full items-center justify-center">
                          <Car className="h-10 w-10 text-slate-300" />
                        </div>
                      )}
                      {vehicle.featured && <Badge className="absolute start-2 top-2 bg-blue-600 text-xs text-white">Featured</Badge>}
                    </div>
                    <CardContent className="p-3">
                      <div className="flex items-start justify-between gap-1">
                        <div>
                          <p className="text-xs text-blue-600">{vehicle.brand.name}</p>
                          <p className="text-sm font-semibold text-slate-900 leading-snug">{vehicle.name}</p>
                          <p className="text-xs text-slate-500">{categoryLabel[vehicle.category]}</p>
                        </div>
                        <div className="shrink-0 text-end">
                          <p className="text-base font-bold text-slate-900">${Number(vehicle.dailyRate).toFixed(0)}</p>
                          <p className="text-xs text-slate-500">/day</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          )}
        </div>

        {/* Branches */}
        <div>
          <h2 className="mb-4 text-xl font-bold text-slate-900">{t("details.ourBranches")}</h2>
          {company.branches.length === 0 ? (
            <p className="text-sm text-slate-500">No branches listed</p>
          ) : (
            <div className="space-y-3">
              {company.branches.map((branch) => (
                <Card key={branch.id} className="border-slate-200">
                  <CardContent className="p-4">
                    <div className="flex items-start gap-3">
                      <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-blue-50">
                        <GitBranch className="h-4 w-4 text-blue-600" />
                      </div>
                      <div className="min-w-0">
                        <p className="font-medium text-slate-900">{branch.name}</p>
                        {branch.city && <p className="text-sm text-slate-500">{branch.city}</p>}
                        {branch.addressLine1 && <p className="mt-1 text-xs text-slate-400 truncate">{branch.addressLine1}</p>}
                        {branch.phone && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-slate-500">
                            <Phone className="h-3 w-3" />{branch.phone}
                          </p>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
