import { notFound, redirect } from "next/navigation"
import { and, eq, gte } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties as propertiesTable, rent_payments, expenses as expensesTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import Link from "next/link"
import { MapPin, Plus, BedDouble, Bath, Edit } from "lucide-react"
import { formatCurrency, getOccupancyRate } from "@/lib/utils"
import { DeletePropertyButton } from "@/components/forms/delete-property-button"
import { AiMaintenanceSummary } from "@/components/forms/ai-maintenance-summary"
import { PropertyRevenueChart } from "@/components/dashboard/property-revenue-chart"
import { PropertyPhotoUpload } from "@/components/forms/property-photo-upload"
import { UnitActions } from "@/components/forms/unit-actions"
import { PropertyMap } from "@/components/maps/property-map"

export default async function PropertyDetailPage({ params }: { params: Promise<{ propertyId: string }> }) {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  const ownerId = await getEffectiveOwnerId(user.id)

  const { propertyId } = await params

  const sixMonthsAgo = new Date()
  sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 5)
  sixMonthsAgo.setDate(1)
  const rangeStart = sixMonthsAgo.toISOString().slice(0, 10)

  const [property, payments, expenses] = await Promise.all([
    db.query.properties.findFirst({
      where: and(eq(propertiesTable.id, propertyId), eq(propertiesTable.user_id, ownerId)),
      with: {
        units: {
          with: {
            current_tenant: { columns: { first_name: true, last_name: true } },
          },
        },
      },
    }),
    db
      .select({ amount: rent_payments.amount, status: rent_payments.status, due_date: rent_payments.due_date })
      .from(rent_payments)
      .where(
        and(
          eq(rent_payments.user_id, ownerId),
          eq(rent_payments.property_id, propertyId),
          gte(rent_payments.due_date, rangeStart)
        )
      ),
    db
      .select({ amount: expensesTable.amount, expense_date: expensesTable.expense_date })
      .from(expensesTable)
      .where(
        and(
          eq(expensesTable.user_id, ownerId),
          eq(expensesTable.property_id, propertyId),
          gte(expensesTable.expense_date, rangeStart)
        )
      ),
  ])

  if (!property) notFound()

  // Build 6-month chart data
  const chartData = Array.from({ length: 6 }, (_, i) => {
    const d = new Date(); d.setMonth(d.getMonth() - (5 - i)); d.setDate(1)
    const key = d.toISOString().slice(0, 7)
    const label = d.toLocaleDateString("en-US", { month: "short" })
    const revenue = (payments ?? []).filter(p => p.status === "paid" && p.due_date?.startsWith(key)).reduce((s, p) => s + Number(p.amount), 0)
    const expense = (expenses ?? []).filter(e => e.expense_date?.startsWith(key)).reduce((s, e) => s + Number(e.amount), 0)
    return { label, revenue, expense }
  })

  const units = property.units ?? []
  const occupied = units.filter((u: any) => u.status === "occupied").length
  const occupancy = getOccupancyRate(occupied, units.length)

  const statusColors: Record<string, string> = {
    occupied:    "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
    vacant:      "text-white/50 bg-white/5 border-white/10",
    maintenance: "text-amber-400 bg-amber-500/10 border-amber-500/20",
    unavailable: "text-red-400 bg-red-500/10 border-red-500/20",
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <div className="flex items-center gap-2 text-sm text-white/40 mb-1">
            <Link href="/properties" className="hover:text-white transition">Properties</Link>
            <span>/</span>
            <span className="text-white/70">{property.name}</span>
          </div>
          <h2 className="text-xl font-bold text-white">{property.name}</h2>
          <div className="mt-1 flex items-center gap-1 text-sm text-white/40">
            <MapPin className="h-3.5 w-3.5" />
            {property.address_line1}, {property.city}{property.state ? `, ${property.state}` : ""}
          </div>
        </div>
        <div className="flex items-center gap-2">
          <AiMaintenanceSummary propertyId={propertyId} />
          <Link
            href={`/properties/${propertyId}/edit`}
            className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2 text-sm text-white/70 hover:border-white/20 hover:text-white transition"
          >
            <Edit className="h-3.5 w-3.5" /> Edit
          </Link>
          <DeletePropertyButton propertyId={propertyId} />
        </div>
      </div>

      {/* Property Photo */}
      <PropertyPhotoUpload propertyId={propertyId} currentImageUrl={property.image_url} />

      {/* Stats row */}
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
        {[
          { label: "Total Units", value: units.length },
          { label: "Occupied", value: occupied },
          { label: "Vacant", value: units.length - occupied },
          { label: "Occupancy", value: `${occupancy}%` },
        ].map((s) => (
          <div key={s.label} className="rounded-xl border border-white/[0.06] bg-[#16161f] p-4">
            <p className="text-xs text-white/40">{s.label}</p>
            <p className="mt-1 text-xl font-bold text-white">{s.value}</p>
          </div>
        ))}
      </div>

      {/* Units */}
      <div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
        <div className="flex items-center justify-between border-b border-white/[0.06] px-5 py-4">
          <h3 className="text-sm font-semibold text-white">Units</h3>
          <Link
            href={`/properties/${propertyId}/units/new`}
            className="flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 transition"
          >
            <Plus className="h-3.5 w-3.5" /> Add Unit
          </Link>
        </div>

        {units.length === 0 ? (
          <div className="py-10 text-center text-sm text-white/30">
            No units yet. Add your first unit.
          </div>
        ) : (
          <div className="divide-y divide-white/[0.04]">
            {units.map((unit: any) => (
              <div key={unit.id} className="flex items-center justify-between px-5 py-4">
                <div className="flex items-center gap-4">
                  <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/5 text-sm font-bold text-white">
                    {unit.unit_number}
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-white">Unit {unit.unit_number}</span>
                      <span className={`rounded-full border px-2 py-0.5 text-xs font-medium ${statusColors[unit.status] ?? statusColors.vacant}`}>
                        {unit.status}
                      </span>
                    </div>
                    <div className="mt-0.5 flex items-center gap-3 text-xs text-white/40">
                      <span className="flex items-center gap-1"><BedDouble className="h-3 w-3" />{unit.bedrooms} bed</span>
                      <span className="flex items-center gap-1"><Bath className="h-3 w-3" />{unit.bathrooms} bath</span>
                      {unit.sq_ft && <span>{unit.sq_ft} sqft</span>}
                    </div>
                    {unit.current_tenant && (
                      <p className="mt-0.5 text-xs text-indigo-400">
                        {unit.current_tenant.first_name} {unit.current_tenant.last_name}
                      </p>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-4">
                  <div className="text-right">
                    <p className="text-sm font-semibold text-white">{formatCurrency(unit.rent_amount)}<span className="text-xs text-white/40">/mo</span></p>
                  </div>
                  <UnitActions propertyId={propertyId} unitId={unit.id} unitNumber={unit.unit_number} />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Location */}
      {property.latitude != null && property.longitude != null && (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
            <MapPin className="h-4 w-4 text-indigo-400" />
            <h3 className="text-sm font-semibold text-white">Location</h3>
          </div>
          <PropertyMap
            className="h-72 w-full"
            markers={[
              {
                id: property.id,
                name: property.name,
                lat: property.latitude,
                lng: property.longitude,
                subtitle: `${property.address_line1}, ${property.city}${property.state ? `, ${property.state}` : ""}`,
              },
            ]}
          />
        </div>
      )}

      {/* Revenue chart */}
      <PropertyRevenueChart data={chartData} />

      {/* Quick links */}
      <div className="flex gap-3 flex-wrap">
        {[
          { label: "View Tenants", href: `/tenants?property=${propertyId}` },
          { label: "Maintenance", href: `/maintenance?property=${propertyId}` },
          { label: "Expenses", href: `/expenses?property=${propertyId}` },
          { label: "Documents", href: `/properties/${propertyId}/documents` },
        ].map((link) => (
          <Link
            key={link.href}
            href={link.href}
            className="rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 hover:border-white/20 hover:text-white transition"
          >
            {link.label}
          </Link>
        ))}
      </div>
    </div>
  )
}
