'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import dayjs from 'dayjs'
import { formatCurrency } from '@rentaldrivego/types'
import { apiFetch } from '@/lib/api'
import DamageInspectionCard, { DamageInspection } from '@/components/reservations/DamageInspectionCard'

interface ReservationDetail {
  id: string
  status: string
  source: string
  startDate: string
  endDate: string
  totalAmount: number
  discountAmount: number
  insuranceTotal: number
  additionalDriverTotal: number
  pricingRulesTotal: number
  paymentStatus: string
  pricingRulesApplied: { name: string; amount: number; type: string }[] | null
  customer: {
    firstName: string
    lastName: string
    email: string
    phone: string | null
    driverLicense: string | null
    licenseValidationStatus: string
    flagged: boolean
  }
  vehicle: {
    make: string
    model: string
    licensePlate: string
  }
  insurances: { id: string; policyName: string; totalCharge: number }[]
  additionalDrivers: {
    id: string
    firstName: string
    lastName: string
    driverLicense: string
    totalCharge: number
    requiresApproval: boolean
    approvedAt: string | null
    approvalNote: string | null
  }[]
}

export default function ReservationDetailPage() {
  const params = useParams<{ id: string }>()
  const [reservation, setReservation] = useState<ReservationDetail | null>(null)
  const [inspections, setInspections] = useState<DamageInspection[]>([])
  const [error, setError] = useState<string | null>(null)
  const [actionError, setActionError] = useState<string | null>(null)
  const [acting, setActing] = useState(false)

  async function loadReservation() {
    try {
      const [reservationData, inspectionData] = await Promise.all([
        apiFetch<ReservationDetail>(`/reservations/${params.id}`),
        apiFetch<DamageInspection[]>(`/reservations/${params.id}/inspections`),
      ])
      setReservation(reservationData)
      setInspections(inspectionData)
      setError(null)
    } catch (err: any) {
      setError(err.message ?? 'Failed to load reservation')
    }
  }

  useEffect(() => {
    loadReservation()
  }, [params.id])

  async function runAction(action: 'confirm' | 'checkin' | 'checkout') {
    setActing(true)
    setActionError(null)
    try {
      await apiFetch(`/reservations/${params.id}/${action}`, {
        method: 'POST',
        body: JSON.stringify({}),
      })
      await loadReservation()
    } catch (err: any) {
      setActionError(err.message ?? `Failed to ${action} reservation`)
    } finally {
      setActing(false)
    }
  }

  async function approveDriver(driverId: string) {
    setActing(true)
    setActionError(null)
    try {
      await apiFetch(`/reservations/${params.id}/additional-drivers/${driverId}/approval`, {
        method: 'PATCH',
        body: JSON.stringify({ approved: true }),
      })
      await loadReservation()
    } catch (err: any) {
      setActionError(err.message ?? 'Failed to approve additional driver')
    } finally {
      setActing(false)
    }
  }

  if (error) return <div className="card p-6 text-sm text-red-600">{error}</div>
  if (!reservation) return <div className="card p-6 text-sm text-slate-500">Loading reservation…</div>

  const checkinInspection = inspections.find((inspection) => inspection.type === 'CHECKIN')
  const checkoutInspection = inspections.find((inspection) => inspection.type === 'CHECKOUT')

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h2 className="text-xl font-semibold text-slate-900">Reservation {reservation.id.slice(-8).toUpperCase()}</h2>
          <p className="mt-1 text-sm text-slate-500">{reservation.source} · {reservation.status} · {reservation.paymentStatus}</p>
        </div>
        <div className="flex flex-wrap gap-3">
          {reservation.status === 'DRAFT' && (
            <button disabled={acting} onClick={() => runAction('confirm')} className="btn-primary">
              {acting ? 'Working…' : 'Confirm reservation'}
            </button>
          )}
          {reservation.status === 'CONFIRMED' && (
            <button disabled={acting} onClick={() => runAction('checkin')} className="btn-primary">
              {acting ? 'Working…' : 'Check in vehicle'}
            </button>
          )}
          {reservation.status === 'ACTIVE' && (
            <button disabled={acting} onClick={() => runAction('checkout')} className="btn-primary">
              {acting ? 'Working…' : 'Check out vehicle'}
            </button>
          )}
        </div>
      </div>

      {actionError && <div className="card p-4 text-sm text-red-600">{actionError}</div>}

      <div className="grid gap-6 lg:grid-cols-2">
        <div className="card p-6">
          <h3 className="mb-4 text-base font-semibold text-slate-900">Customer</h3>
          <div className="space-y-2 text-sm">
            <p className="font-medium text-slate-900">{reservation.customer.firstName} {reservation.customer.lastName}</p>
            <p className="text-slate-600">{reservation.customer.email}</p>
            <p className="text-slate-600">{reservation.customer.phone ?? 'No phone provided'}</p>
            <p className="text-slate-600">License: {reservation.customer.driverLicense ?? 'Not captured'}</p>
            <div className="flex flex-wrap gap-2 pt-2">
              <span className="badge-gray">{reservation.customer.licenseValidationStatus}</span>
              {reservation.customer.flagged && <span className="badge-red">Flagged</span>}
            </div>
          </div>
        </div>

        <div className="card p-6">
          <h3 className="mb-4 text-base font-semibold text-slate-900">Vehicle</h3>
          <div className="space-y-2 text-sm text-slate-600">
            <p className="font-medium text-slate-900">{reservation.vehicle.make} {reservation.vehicle.model}</p>
            <p>{reservation.vehicle.licensePlate}</p>
            <p>{dayjs(reservation.startDate).format('MMM D, YYYY')} - {dayjs(reservation.endDate).format('MMM D, YYYY')}</p>
          </div>
        </div>
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
        <div className="space-y-6">
          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">Charges</h3>
            <dl className="grid gap-3 text-sm sm:grid-cols-2">
              <div><dt className="text-slate-500">Discount</dt><dd className="text-slate-900">{formatCurrency(reservation.discountAmount, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">Insurance</dt><dd className="text-slate-900">{formatCurrency(reservation.insuranceTotal, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">Additional drivers</dt><dd className="text-slate-900">{formatCurrency(reservation.additionalDriverTotal, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">Pricing adjustments</dt><dd className="text-slate-900">{formatCurrency(reservation.pricingRulesTotal, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">Grand total</dt><dd className="font-semibold text-slate-900">{formatCurrency(reservation.totalAmount, 'MAD')}</dd></div>
            </dl>

            {reservation.insurances.length > 0 && (
              <div className="mt-5">
                <p className="mb-2 text-sm font-semibold text-slate-900">Applied insurance</p>
                <div className="space-y-2">
                  {reservation.insurances.map((insurance) => (
                    <div key={insurance.id} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3 text-sm">
                      <span className="text-slate-700">{insurance.policyName}</span>
                      <span className="font-semibold text-slate-900">{formatCurrency(insurance.totalCharge, 'MAD')}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {reservation.pricingRulesApplied && reservation.pricingRulesApplied.length > 0 && (
              <div className="mt-5">
                <p className="mb-2 text-sm font-semibold text-slate-900">Pricing rules applied</p>
                <div className="space-y-2">
                  {reservation.pricingRulesApplied.map((rule) => (
                    <div key={`${rule.name}-${rule.amount}`} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3 text-sm">
                      <span className="text-slate-700">{rule.name}</span>
                      <span className={rule.amount < 0 ? 'font-semibold text-emerald-700' : 'font-semibold text-amber-700'}>
                        {rule.amount < 0 ? '-' : '+'}{formatCurrency(Math.abs(rule.amount), 'MAD')}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          <DamageInspectionCard
            reservationId={reservation.id}
            type="CHECKIN"
            initialInspection={checkinInspection}
            onSaved={(inspection) => setInspections((current) => [...current.filter((item) => item.type !== inspection.type), inspection])}
          />
          <DamageInspectionCard
            reservationId={reservation.id}
            type="CHECKOUT"
            initialInspection={checkoutInspection}
            onSaved={(inspection) => setInspections((current) => [...current.filter((item) => item.type !== inspection.type), inspection])}
          />
        </div>

        <div className="space-y-6">
          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">Additional drivers</h3>
            <div className="space-y-3">
              {reservation.additionalDrivers.map((driver) => (
                <div key={driver.id} className="rounded-2xl border border-slate-200 p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="font-medium text-slate-900">{driver.firstName} {driver.lastName}</p>
                      <p className="text-sm text-slate-500">License: {driver.driverLicense}</p>
                      <p className="mt-1 text-sm text-slate-600">Charge: {formatCurrency(driver.totalCharge, 'MAD')}</p>
                    </div>
                    {driver.requiresApproval && !driver.approvedAt ? (
                      <button onClick={() => approveDriver(driver.id)} disabled={acting} className="rounded-full bg-slate-900 px-4 py-2 text-xs font-semibold text-white">
                        Approve
                      </button>
                    ) : (
                      <span className={driver.approvedAt ? 'badge-green' : 'badge-gray'}>
                        {driver.approvedAt ? 'Approved' : 'No approval needed'}
                      </span>
                    )}
                  </div>
                  {driver.approvalNote && <p className="mt-2 text-xs text-amber-700">{driver.approvalNote}</p>}
                </div>
              ))}
              {reservation.additionalDrivers.length === 0 && (
                <div className="text-sm text-slate-400">No additional drivers were added to this reservation.</div>
              )}
            </div>
          </div>

          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">Inspection summary</h3>
            <div className="space-y-3 text-sm">
              <div className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <span className="text-slate-600">Check-in inspection</span>
                <span className={checkinInspection ? 'badge-green' : 'badge-gray'}>{checkinInspection ? 'Saved' : 'Pending'}</span>
              </div>
              <div className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <span className="text-slate-600">Check-out inspection</span>
                <span className={checkoutInspection ? 'badge-green' : 'badge-gray'}>{checkoutInspection ? 'Saved' : 'Pending'}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
