'use client'

import { useEffect, useState } from 'react'
import { Calendar, Car, Users, DollarSign, AlertTriangle, Clock, XCircle } from 'lucide-react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts'
import StatCard from '@/components/ui/StatCard'
import { apiFetch } from '@/lib/api'
import dayjs from 'dayjs'
import { formatCurrency } from '@rentaldrivego/types'

interface DashboardData {
  kpis: {
    totalBookings: number
    activeVehicles: number
    monthlyRevenue: number
    totalCustomers: number
    bookingsChange: number
    vehiclesChange: number
    revenueChange: number
    customersChange: number
  }
  recentReservations: {
    id: string
    bookingRef: string
    customerName: string
    vehicleName: string
    startDate: string
    endDate: string
    status: string
    totalAmount: number
  }[]
  sourceBreakdown: { source: string; count: number; revenue: number }[]
  subscription: {
    status: string
    planName: string
    trialEndsAt: string | null
  }
}

const STATUS_COLORS: Record<string, string> = {
  CONFIRMED: 'badge-blue',
  PENDING: 'badge-amber',
  ACTIVE: 'badge-green',
  COMPLETED: 'badge-gray',
  CANCELLED: 'badge-red',
}

function SubscriptionBanner({ status, planName, trialEndsAt }: { status: string; planName: string; trialEndsAt: string | null }) {
  if (status === 'ACTIVE') return null

  const configs: Record<string, { bg: string; icon: React.ReactNode; message: string }> = {
    TRIALING: {
      bg: 'bg-blue-50 border-blue-200 text-blue-800',
      icon: <Clock className="w-4 h-4" />,
      message: trialEndsAt
        ? `You're on a free trial. Trial ends ${dayjs(trialEndsAt).format('MMM D, YYYY')}.`
        : "You're on a free trial.",
    },
    PAST_DUE: {
      bg: 'bg-amber-50 border-amber-200 text-amber-800',
      icon: <AlertTriangle className="w-4 h-4" />,
      message: 'Your payment is past due. Please update your billing information.',
    },
    SUSPENDED: {
      bg: 'bg-red-50 border-red-200 text-red-800',
      icon: <XCircle className="w-4 h-4" />,
      message: 'Your account has been suspended. Please contact support or renew your subscription.',
    },
  }

  const config = configs[status]
  if (!config) return null

  return (
    <div className={`flex items-center gap-3 px-4 py-3 rounded-xl border mb-6 ${config.bg}`}>
      {config.icon}
      <p className="text-sm font-medium">{config.message}</p>
      <a href="/dashboard/billing" className="ml-auto text-sm font-semibold underline hover:no-underline">
        Manage billing →
      </a>
    </div>
  )
}

export default function DashboardPage() {
  const [data, setData] = useState<DashboardData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    apiFetch<DashboardData>('/analytics/dashboard')
      .then(setData)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="card p-6 text-center">
        <p className="text-red-600 font-medium">Failed to load dashboard</p>
        <p className="text-slate-500 text-sm mt-1">{error}</p>
      </div>
    )
  }

  const kpis = data?.kpis ?? { totalBookings: 0, activeVehicles: 0, monthlyRevenue: 0, totalCustomers: 0, bookingsChange: 0, vehiclesChange: 0, revenueChange: 0, customersChange: 0 }

  return (
    <div className="space-y-6">
      {data?.subscription && (
        <SubscriptionBanner
          status={data.subscription.status}
          planName={data.subscription.planName}
          trialEndsAt={data.subscription.trialEndsAt}
        />
      )}

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Total Bookings"
          value={kpis.totalBookings.toLocaleString()}
          change={kpis.bookingsChange}
          icon={Calendar}
          iconColor="text-blue-600"
          iconBg="bg-blue-50"
        />
        <StatCard
          title="Active Vehicles"
          value={kpis.activeVehicles.toLocaleString()}
          change={kpis.vehiclesChange}
          icon={Car}
          iconColor="text-green-600"
          iconBg="bg-green-50"
        />
        <StatCard
          title="Monthly Revenue"
          value={formatCurrency(kpis.monthlyRevenue, 'MAD')}
          change={kpis.revenueChange}
          icon={DollarSign}
          iconColor="text-amber-600"
          iconBg="bg-amber-50"
        />
        <StatCard
          title="Total Customers"
          value={kpis.totalCustomers.toLocaleString()}
          change={kpis.customersChange}
          icon={Users}
          iconColor="text-purple-600"
          iconBg="bg-purple-50"
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Booking Sources Chart */}
        <div className="card p-6 lg:col-span-2">
          <h2 className="text-base font-semibold text-slate-900 mb-4">Booking Sources</h2>
          {data?.sourceBreakdown && data.sourceBreakdown.length > 0 ? (
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={data.sourceBreakdown}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                <XAxis dataKey="source" tick={{ fontSize: 12 }} />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip
                  contentStyle={{ borderRadius: '8px', border: '1px solid #e2e8f0', fontSize: '12px' }}
                />
                <Legend wrapperStyle={{ fontSize: '12px' }} />
                <Bar dataKey="count" fill="#3b82f6" name="Bookings" radius={[4, 4, 0, 0]} />
                <Bar dataKey="revenue" fill="#10b981" name="Revenue (centimes)" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-48 flex items-center justify-center text-slate-400 text-sm">
              No booking data available yet
            </div>
          )}
        </div>

        {/* Quick stats */}
        <div className="card p-6">
          <h2 className="text-base font-semibold text-slate-900 mb-4">Quick Stats</h2>
          <div className="space-y-4">
            {(data?.sourceBreakdown ?? []).map((item) => (
              <div key={item.source} className="flex items-center justify-between">
                <span className="text-sm text-slate-600 capitalize">{item.source.toLowerCase()}</span>
                <div className="text-right">
                  <span className="text-sm font-semibold text-slate-900">{item.count}</span>
                  <p className="text-xs text-slate-400">{formatCurrency(item.revenue, 'MAD')}</p>
                </div>
              </div>
            ))}
            {(!data?.sourceBreakdown || data.sourceBreakdown.length === 0) && (
              <p className="text-sm text-slate-400">No data yet</p>
            )}
          </div>
        </div>
      </div>

      {/* Recent Reservations */}
      <div className="card">
        <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
          <h2 className="text-base font-semibold text-slate-900">Recent Reservations</h2>
          <a href="/dashboard/reservations" className="text-sm text-blue-600 hover:text-blue-700 font-medium">
            View all →
          </a>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Booking #</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Customer</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Vehicle</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Dates</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Status</th>
                <th className="text-right px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {(data?.recentReservations ?? []).map((res) => (
                <tr key={res.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-6 py-3">
                    <a href={`/dashboard/reservations/${res.id}`} className="text-sm font-medium text-blue-600 hover:text-blue-700">
                      #{res.bookingRef}
                    </a>
                  </td>
                  <td className="px-6 py-3 text-sm text-slate-700">{res.customerName}</td>
                  <td className="px-6 py-3 text-sm text-slate-700">{res.vehicleName}</td>
                  <td className="px-6 py-3 text-sm text-slate-500">
                    {dayjs(res.startDate).format('MMM D')} – {dayjs(res.endDate).format('MMM D, YYYY')}
                  </td>
                  <td className="px-6 py-3">
                    <span className={STATUS_COLORS[res.status] ?? 'badge-gray'}>
                      {res.status}
                    </span>
                  </td>
                  <td className="px-6 py-3 text-sm font-semibold text-slate-900 text-right">
                    {formatCurrency(res.totalAmount, 'MAD')}
                  </td>
                </tr>
              ))}
              {(!data?.recentReservations || data.recentReservations.length === 0) && (
                <tr>
                  <td colSpan={6} className="px-6 py-8 text-center text-sm text-slate-400">
                    No reservations yet. Once customers book vehicles, they'll appear here.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
