import { notFound, redirect } from "next/navigation"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { leases as leasesTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getAccountContext } from "@/lib/account"
import { listEsignConnections, listRequestsForLease } from "@/lib/esign"
import Link from "next/link"
import { FileText } from "lucide-react"
import { formatCurrency, formatDate, daysUntil } from "@/lib/utils"
import { cn } from "@/lib/utils"
import { LeaseActions } from "@/components/forms/lease-actions"
import { EsignLease } from "@/components/forms/esign-lease"
import { LeaseDocument } from "@/components/forms/lease-document"

const ESIGN_LABEL: Record<string, string> = { docusign: "DocuSign", dropbox_sign: "Dropbox Sign" }

export const metadata = { title: "Lease" }

const statusColors: Record<string, string> = {
  active:     "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
  expired:    "text-red-400 bg-red-500/10 border-red-500/20",
  terminated: "text-white/40 bg-white/5 border-white/10",
  renewed:    "text-blue-400 bg-blue-500/10 border-blue-500/20",
}

const leaseTypeLabels: Record<string, string> = {
  fixed:          "Fixed Term",
  month_to_month: "Month-to-Month",
}

function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between gap-4 py-3">
      <span className="text-sm text-white/40">{label}</span>
      <span className="text-right text-sm font-medium text-white">{children}</span>
    </div>
  )
}

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

  const ctx = await getAccountContext(user.id)
  const ownerId = ctx.ownerId

  const { leaseId } = await params

  const lease = await db.query.leases.findFirst({
    where: and(eq(leasesTable.id, leaseId), eq(leasesTable.user_id, ownerId)),
    with: {
      tenant: { columns: { id: true, first_name: true, last_name: true, email: true } },
      property: { columns: { name: true } },
      unit: { columns: { unit_number: true } },
    },
  })

  if (!lease) notFound()

  const esignRequests = await listRequestsForLease(ownerId, leaseId)
  const esignConnections = await listEsignConnections(ownerId)
  const connectedProviders = esignConnections
    .filter((c) => c.status !== "revoked")
    .map((c) => ({ id: c.provider, label: ESIGN_LABEL[c.provider] ?? c.provider }))
  const canSendEsign =
    ctx.canWrite && !!lease.document_url && !!lease.tenant?.email && connectedProviders.length > 0
  const esignDisabledReason = !ctx.canWrite
    ? "You have read-only access."
    : !lease.document_url
      ? "Upload a lease document to enable e-signature."
      : !lease.tenant?.email
        ? "The tenant has no email address on file."
        : ""

  const days = daysUntil(lease.lease_end)
  const totalDays = Math.max(
    0,
    Math.round(
      (new Date(lease.lease_end).getTime() - new Date(lease.lease_start).getTime()) /
        (1000 * 60 * 60 * 24)
    )
  )

  return (
    <div className="mx-auto max-w-4xl space-y-6">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-white/40">
        <Link href="/leases" className="hover:text-white transition">Leases</Link>
        <span>/</span>
        <span className="text-white/70">
          {lease.tenant?.first_name} {lease.tenant?.last_name}
        </span>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-center gap-4">
          <div className="flex h-14 w-14 items-center justify-center rounded-2xl border border-indigo-500/20 bg-indigo-600/20 text-indigo-400">
            <FileText className="h-6 w-6" />
          </div>
          <div>
            <div className="flex items-center gap-3">
              <h2 className="text-xl font-bold text-white">
                {lease.tenant?.first_name} {lease.tenant?.last_name}
              </h2>
              <span className={cn("rounded-md border px-2 py-0.5 text-xs font-medium capitalize", statusColors[lease.status] ?? statusColors.active)}>
                {lease.status}
              </span>
            </div>
            <p className="mt-1 text-sm text-white/50">
              {lease.property?.name} · Unit {lease.unit?.unit_number ?? "—"}
            </p>
          </div>
        </div>

        <LeaseActions lease={lease} />
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Main */}
        <div className="lg:col-span-2 space-y-6">
          {/* Term */}
          <div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
            <div className="border-b border-white/[0.06] px-5 py-4">
              <h3 className="text-sm font-semibold text-white">Lease Term</h3>
            </div>
            <div className="divide-y divide-white/[0.04] px-5">
              <InfoRow label="Start date">{formatDate(lease.lease_start)}</InfoRow>
              <InfoRow label="End date">{formatDate(lease.lease_end)}</InfoRow>
              <InfoRow label="Duration">{totalDays} days</InfoRow>
              <InfoRow label={days <= 0 ? "Expired" : "Ends in"}>
                {lease.status === "active"
                  ? days <= 0
                    ? <span className="text-red-400">{Math.abs(days)} days ago</span>
                    : <span className={days <= 30 ? "text-amber-400" : "text-white"}>{days} days</span>
                  : <span className="text-white/40">—</span>}
              </InfoRow>
            </div>
          </div>

          {/* Financials */}
          <div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
            <div className="border-b border-white/[0.06] px-5 py-4">
              <h3 className="text-sm font-semibold text-white">Financials</h3>
            </div>
            <div className="divide-y divide-white/[0.04] px-5">
              <InfoRow label="Monthly rent">
                {formatCurrency(lease.rent_amount)}<span className="text-xs text-white/30">/mo</span>
              </InfoRow>
              <InfoRow label="Security deposit">
                {lease.security_deposit != null ? formatCurrency(lease.security_deposit) : <span className="text-white/40">—</span>}
              </InfoRow>
            </div>
          </div>

          {/* Notes */}
          {lease.notes && (
            <div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
              <div className="border-b border-white/[0.06] px-5 py-4">
                <h3 className="text-sm font-semibold text-white">Notes</h3>
              </div>
              <p className="whitespace-pre-wrap px-5 py-4 text-sm text-white/60">{lease.notes}</p>
            </div>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-4">
          <div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-5 space-y-3">
            <h3 className="text-xs font-medium uppercase tracking-wider text-white/30">Details</h3>
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm text-white/40">Tenant</span>
                {lease.tenant?.id ? (
                  <Link href={`/tenants/${lease.tenant.id}`} className="text-sm font-medium text-indigo-400 hover:text-indigo-300 transition">
                    {lease.tenant.first_name} {lease.tenant.last_name}
                  </Link>
                ) : (
                  <span className="text-sm font-medium text-white">
                    {lease.tenant?.first_name} {lease.tenant?.last_name}
                  </span>
                )}
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-white/40">Property</span>
                <span className="text-sm font-medium text-white">{lease.property?.name}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-white/40">Unit</span>
                <span className="text-sm font-medium text-white">{lease.unit?.unit_number ?? "—"}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-white/40">Type</span>
                <span className="text-sm font-medium text-white">{leaseTypeLabels[lease.lease_type] ?? lease.lease_type}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-white/40">Auto-renew</span>
                <span className={cn("text-sm font-medium", lease.auto_renew ? "text-emerald-400" : "text-white/40")}>
                  {lease.auto_renew ? "Enabled" : "Disabled"}
                </span>
              </div>
            </div>
          </div>

          <LeaseDocument leaseId={leaseId} documentUrl={lease.document_url} canWrite={ctx.canWrite} />

          <EsignLease
            leaseId={leaseId}
            connected={connectedProviders}
            requests={esignRequests}
            canSend={canSendEsign}
            disabledReason={esignDisabledReason}
          />
        </div>
      </div>
    </div>
  )
}
