'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { Calendar, Car, Users, DollarSign, AlertTriangle, Clock, XCircle, Plus, BarChart3, FileText, TrendingUp, MapPin } from 'lucide-react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts'
import StatCard from '@/components/ui/StatCard'
import { EMPLOYEE_PROFILE_KEY, apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'
import { formatCurrency } from '@rentaldrivego/types'

/**
 * Location breakdown item — requires backend field on /analytics/dashboard.
 * Flagged as a contract change (not faked).
 */
interface LocationBreakdown {
  name: string
  bookingCount: number
  revenue: number
  /** 0–100 utilization percentage */
  utilizationPct: number
}

interface DashboardData {
  kpis: {
    totalBookings: number
    activeVehicles: number
    monthlyRevenue: number
    totalCustomers: number
    bookingsChange: number
    vehiclesChange: number
    revenueChange: number
    customersChange: number
    /** Requires backend field — flagged as contract change */
    utilizationRate?: number
    /** Requires backend field — flagged as contract change */
    revenuePerVehicle?: number
    /** Requires backend field — flagged as contract change */
    fulfillmentRate?: 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 }[]
  /** Requires backend field — flagged as contract change */
  locationBreakdown?: LocationBreakdown[]
  subscription: {
    status: string
    planName: string
    trialEndsAt: string | null
  }
}

interface EmployeeProfile {
  role?: string
  firstName?: string
  lastName?: string
  email?: string
}

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

interface QuickAction {
  icon: React.ReactNode
  label: string
  href: string
  color: string
}

function QuickActionsSection({ actions }: { actions: QuickAction[] }) {
  return (
    <div className="flex flex-wrap gap-3">
      {actions.map((action) => (
        <Link
          key={action.href}
          href={action.href}
          className={`flex items-center gap-2 rounded-lg border border-blue-400/15 bg-blue-500/[0.06] px-4 py-3 transition-all hover:border-blue-400/35 hover:bg-blue-500/10 ${action.color}`}
        >
          {action.icon}
          <span className="text-sm font-medium">{action.label}</span>
        </Link>
      ))}
    </div>
  )
}

function SubscriptionBanner({
  status,
  trialEndsAt,
  trialEndsMsg,
  trialActiveMsg,
  pastDueMsg,
  suspendedMsg,
  manageBillingLabel,
}: {
  status: string
  trialEndsAt: string | null
  trialEndsMsg: (date: string) => string
  trialActiveMsg: string
  pastDueMsg: string
  suspendedMsg: string
  manageBillingLabel: string
}) {
  if (status === 'ACTIVE') return null

  const localeDate = trialEndsAt
    ? new Date(trialEndsAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })
    : ''

  const configs: Record<string, { bg: string; icon: React.ReactNode; message: string }> = {
    TRIALING: {
      bg: 'bg-blue-500/10 border-blue-400/25 text-blue-200',
      icon: <Clock className="w-4 h-4" />,
      message: trialEndsAt ? trialEndsMsg(localeDate) : trialActiveMsg,
    },
    PAST_DUE: {
      bg: 'bg-orange-500/10 border-orange-400/25 text-orange-200',
      icon: <AlertTriangle className="w-4 h-4" />,
      message: pastDueMsg,
    },
    SUSPENDED: {
      bg: 'bg-red-500/10 border-red-400/25 text-red-200',
      icon: <XCircle className="w-4 h-4" />,
      message: suspendedMsg,
    },
  }

  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>
      <Link href="/subscription" className="ml-auto text-sm font-semibold underline hover:no-underline">
        {manageBillingLabel}
      </Link>
    </div>
  )
}

function BranchPerformanceList({
  locations,
  formatCurrencyFn,
}: {
  locations: LocationBreakdown[]
  formatCurrencyFn: (amount: number, currency: string) => string
}) {
  const maxCount = Math.max(...locations.map((l) => l.bookingCount), 1)

  return (
    <div className="glass-card p-6">
      <div className="mb-4 flex items-center gap-2">
        <MapPin className="h-4 w-4 text-orange-700 dark:text-orange-300" />
        <h2 className="text-base font-semibold text-blue-950 dark:text-slate-100">Location Performance</h2>
      </div>
      <div className="space-y-4">
        {locations.map((loc) => (
          <div key={loc.name}>
            <div className="mb-1 flex items-center justify-between">
              <span className="text-sm font-medium text-blue-950 dark:text-slate-100">{loc.name}</span>
              <span className="text-xs font-mono text-slate-500 dark:text-slate-400">
                {loc.bookingCount} bookings · {formatCurrencyFn(loc.revenue, 'MAD')}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <div className="progress-bar flex-1">
                <div
                  className="progress-fill blue"
                  style={{ width: `${(loc.bookingCount / maxCount) * 100}%` }}
                />
              </div>
              <span className="w-8 text-right text-xs font-mono text-slate-500 dark:text-slate-400">
                {loc.utilizationPct}%
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default function DashboardPage() {
  const { dict, language, theme } = useDashboardI18n()
  const d = dict.dashboardPage
  const nav = dict.nav
  const localeCode = language === 'fr' ? 'fr-FR' : language === 'ar' ? 'ar-MA' : 'en-US'
  const isDark = theme === 'dark'
  const chartGrid = isDark ? 'rgba(59,130,246,0.14)' : 'rgba(37,99,235,0.14)'
  const chartAxis = isDark ? 'rgba(59,130,246,0.20)' : 'rgba(37,99,235,0.22)'
  const chartText = isDark ? '#8899b4' : '#64748b'
  const chartTooltipBg = isDark ? '#111827' : '#ffffff'
  const chartTooltipText = isDark ? '#e8edf5' : '#172554'

  const [data, setData] = useState<DashboardData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<{ code: string; message: string } | null>(null)
  const [employeeRole, setEmployeeRole] = useState<string | null>(null)
  const [employeeName, setEmployeeName] = useState<string | null>(null)

  useEffect(() => {
    try {
      const cached = window.localStorage.getItem(EMPLOYEE_PROFILE_KEY)
      if (!cached) return
      const profile = JSON.parse(cached) as EmployeeProfile
      setEmployeeRole(profile.role ?? null)
      const fullName = [profile.firstName, profile.lastName].filter(Boolean).join(' ') || null
      setEmployeeName(fullName)
    } catch {}
  }, [])

  useEffect(() => {
    apiFetch<DashboardData>('/analytics/dashboard')
      .then(setData)
      .catch((err) => setError({ code: err.code ?? '', message: 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) {
    const errorMsg = error.code === 'forbidden' ? d.forbidden : error.message
    return (
      <div className="card p-6 text-center">
        <p className="text-slate-500 text-sm dark:text-slate-400">{errorMsg}</p>
      </div>
    )
  }

  const kpis = data?.kpis ?? { totalBookings: 0, activeVehicles: 0, monthlyRevenue: 0, totalCustomers: 0, bookingsChange: 0, vehiclesChange: 0, revenueChange: 0, customersChange: 0 }
  const canViewRevenue = employeeRole !== 'AGENT'

  const formatDate = (iso: string) =>
    new Date(iso).toLocaleDateString(localeCode, { month: 'short', day: 'numeric' })
  const formatDateYear = (iso: string) =>
    new Date(iso).toLocaleDateString(localeCode, { month: 'short', day: 'numeric', year: 'numeric' })

  return (
    <div className="space-y-6">
      {/* Welcome Section */}
      <div>
        <h1 className="mb-1 text-2xl font-semibold text-blue-950 dark:text-slate-50">
          Welcome back{employeeName ? `, ${employeeName}` : ''}!
        </h1>
        <p className="mb-4 text-sm text-slate-500 dark:text-slate-400">
          Here's what's happening with your fleet today
        </p>
      </div>

      {/* Quick Actions */}
      <QuickActionsSection
        actions={[
          {
            icon: <Plus className="w-4 h-4" />,
            label: 'New Reservation',
            href: '/reservations/new',
            color: 'text-blue-700 dark:text-blue-300',
          },
          {
            icon: <Car className="w-4 h-4" />,
            label: nav.fleet,
            href: '/fleet',
            color: 'text-emerald-700 dark:text-emerald-300',
          },
          {
            icon: <Users className="w-4 h-4" />,
            label: nav.customers,
            href: '/customers',
            color: 'text-orange-700 dark:text-orange-300',
          },
          {
            icon: <FileText className="w-4 h-4" />,
            label: nav.reports,
            href: '/reports',
            color: 'text-orange-700 dark:text-orange-300',
          },
        ]}
      />

      {data?.subscription && (
        <SubscriptionBanner
          status={data.subscription.status}
          trialEndsAt={data.subscription.trialEndsAt}
          trialEndsMsg={d.trialEnds}
          trialActiveMsg={d.trialActive}
          pastDueMsg={d.pastDueMsg}
          suspendedMsg={d.suspendedMsg}
          manageBillingLabel={d.manageBilling}
        />
      )}

      {/* KPI Cards */}
      <div className={`grid grid-cols-1 gap-4 sm:grid-cols-2 ${canViewRevenue ? 'lg:grid-cols-4' : 'lg:grid-cols-3'}`}>
        <StatCard
          title={d.kpiTotalBookings}
          value={kpis.totalBookings.toLocaleString()}
          change={kpis.bookingsChange}
          vsLastMonthLabel={d.vsLastMonth}
          icon={Calendar}
          iconColor="text-blue-700 dark:text-blue-300"
          iconBg="bg-blue-100/80 dark:bg-blue-500/10"
          pulse
        />
        <StatCard
          title={d.kpiActiveVehicles}
          value={kpis.activeVehicles.toLocaleString()}
          change={kpis.vehiclesChange}
          vsLastMonthLabel={d.vsLastMonth}
          icon={Car}
          iconColor="text-emerald-700 dark:text-emerald-300"
          iconBg="bg-emerald-100/80 dark:bg-emerald-500/10"
        />
        {canViewRevenue ? (
          <StatCard
            title={d.kpiMonthlyRevenue}
            value={formatCurrency(kpis.monthlyRevenue, 'MAD')}
            change={kpis.revenueChange}
            vsLastMonthLabel={d.vsLastMonth}
            icon={DollarSign}
            iconColor="text-orange-700 dark:text-orange-300"
            iconBg="bg-orange-100/80 dark:bg-orange-500/10"
            valueGradient
          />
        ) : null}
        <StatCard
          title={d.kpiTotalCustomers}
          value={kpis.totalCustomers.toLocaleString()}
          change={kpis.customersChange}
          vsLastMonthLabel={d.vsLastMonth}
          icon={Users}
          iconColor="text-blue-700 dark:text-blue-300"
          iconBg="bg-blue-100/80 dark:bg-blue-500/10"
        />
      </div>

      {/* New metrics row — contract change flag */}
      {kpis.utilizationRate !== undefined && (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          <StatCard
            title="Utilization Rate"
            value={`${kpis.utilizationRate}%`}
            icon={TrendingUp}
            iconColor="text-blue-700 dark:text-blue-300"
            iconBg="bg-blue-100/80 dark:bg-blue-500/10"
            progressPercent={kpis.utilizationRate}
            target={100}
          />
          <StatCard
            title="Revenue / Vehicle"
            value={formatCurrency(kpis.revenuePerVehicle ?? 0, 'MAD')}
            icon={DollarSign}
            iconColor="text-orange-700 dark:text-orange-300"
            iconBg="bg-orange-100/80 dark:bg-orange-500/10"
          />
          <StatCard
            title="Fulfillment Rate"
            value={`${kpis.fulfillmentRate ?? 0}%`}
            icon={BarChart3}
            iconColor="text-emerald-700 dark:text-emerald-300"
            iconBg="bg-emerald-100/80 dark:bg-emerald-500/10"
            progressPercent={kpis.fulfillmentRate ?? 0}
            target={100}
          />
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left column — 2/3: Booking Sources + Location Performance */}
        <div className="lg:col-span-2 space-y-6">
          <div className="card p-6">
            <h2 className="mb-4 text-base font-semibold text-blue-950 dark:text-slate-100">{d.bookingSources}</h2>
            {data?.sourceBreakdown && data.sourceBreakdown.length > 0 ? (
              <ResponsiveContainer width="100%" height={240}>
                <BarChart data={data.sourceBreakdown}>
                  <CartesianGrid strokeDasharray="3 3" stroke={chartGrid} />
                  <XAxis dataKey="source" tick={{ fontSize: 12, fill: chartText }} axisLine={{ stroke: chartAxis }} tickLine={false} />
                  <YAxis tick={{ fontSize: 12, fill: chartText }} axisLine={{ stroke: chartAxis }} tickLine={false} />
                  <Tooltip
                    contentStyle={{ borderRadius: '8px', border: `1px solid ${chartAxis}`, background: chartTooltipBg, color: chartTooltipText, fontSize: '12px' }}
                    cursor={{ fill: 'rgba(59,130,246,0.08)' }}
                  />
                  <Legend wrapperStyle={{ fontSize: '12px', color: chartText }} />
                  <Bar dataKey="count" fill="#3b82f6" name={d.barBookings} radius={[4, 4, 0, 0]} />
                  <Bar dataKey="revenue" fill="#f97316" name={d.barRevenue} radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-48 flex items-center justify-center text-slate-400 text-sm">
                {d.noBookingData}
              </div>
            )}
          </div>

          {data?.locationBreakdown && data.locationBreakdown.length > 0 ? (
            <BranchPerformanceList
              locations={data.locationBreakdown}
              formatCurrencyFn={(a, c) => formatCurrency(a, c as 'MAD')}
            />
          ) : null}
        </div>

        {/* Right column — 1/3: Quick Stats */}
        <div className="card p-6">
          <h2 className="mb-4 text-base font-semibold text-blue-950 dark:text-slate-100">{d.quickStats}</h2>
          <div className="space-y-4">
            {(data?.sourceBreakdown ?? []).map((item) => (
              <div key={item.source} className="flex items-center justify-between">
                <span className="text-sm capitalize text-slate-500 dark:text-slate-400">{item.source.toLowerCase()}</span>
                <div className="text-right">
                  <span className="text-sm font-semibold text-blue-950 dark:text-slate-100">{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">{d.noData}</p>
            )}
          </div>
        </div>
      </div>

      {/* Recent Reservations */}
      <div className="card">
        <div className="flex items-center justify-between border-b border-blue-200/70 px-6 py-4 dark:border-blue-400/10">
          <h2 className="text-base font-semibold text-blue-950 dark:text-slate-100">{d.recentReservations}</h2>
          <Link href="/reservations" className="text-sm font-medium text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-200">
            {d.viewAll}
          </Link>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-blue-200/70 dark:border-blue-400/10">
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{d.colBookingNum}</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{d.colCustomer}</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{d.colVehicle}</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{d.colDates}</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{d.colStatus}</th>
                <th className="text-right px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{d.colTotal}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-blue-200/70 dark:divide-blue-400/10">
              {(data?.recentReservations ?? []).map((res) => (
                <tr key={res.id} className="transition-colors hover:bg-blue-500/[0.06]">
                  <td className="px-6 py-3">
                    <Link href={`/reservations/${res.id}`} className="text-sm font-medium text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-200">
                      #{res.bookingRef}
                    </Link>
                  </td>
                  <td className="px-6 py-3 text-sm text-slate-700 dark:text-slate-300">{res.customerName}</td>
                  <td className="px-6 py-3 text-sm text-slate-700 dark:text-slate-300">{res.vehicleName}</td>
                  <td className="px-6 py-3 text-sm text-slate-500 dark:text-slate-400">
                    {formatDate(res.startDate)} – {formatDateYear(res.endDate)}
                  </td>
                  <td className="px-6 py-3">
                    <span className={STATUS_COLORS[res.status] ?? 'badge-gray'}>
                      {d.statusLabels[res.status as keyof typeof d.statusLabels] ?? res.status}
                    </span>
                  </td>
                  <td className="px-6 py-3 text-right text-sm font-semibold text-blue-950 dark:text-slate-100">
                    {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">
                    {d.noReservations}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
