'use client'

import Link from 'next/link'
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 { EMPLOYEE_PROFILE_KEY, apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'
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
  }
}

interface EmployeeProfile {
  role?: string
}

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

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-50 border-blue-200 text-blue-800',
      icon: <Clock className="w-4 h-4" />,
      message: trialEndsAt ? trialEndsMsg(localeDate) : trialActiveMsg,
    },
    PAST_DUE: {
      bg: 'bg-orange-50 border-orange-200 text-orange-800',
      icon: <AlertTriangle className="w-4 h-4" />,
      message: pastDueMsg,
    },
    SUSPENDED: {
      bg: 'bg-red-50 border-red-200 text-red-800',
      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>
  )
}

export default function DashboardPage() {
  const { dict, language } = useDashboardI18n()
  const d = dict.dashboardPage
  const localeCode = language === 'fr' ? 'fr-FR' : language === 'ar' ? 'ar-MA' : 'en-US'

  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)

  useEffect(() => {
    try {
      const cached = window.localStorage.getItem(EMPLOYEE_PROFILE_KEY)
      if (!cached) return
      const profile = JSON.parse(cached) as EmployeeProfile
      setEmployeeRole(profile.role ?? null)
    } 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">{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">
      {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-600"
          iconBg="bg-blue-50"
        />
        <StatCard
          title={d.kpiActiveVehicles}
          value={kpis.activeVehicles.toLocaleString()}
          change={kpis.vehiclesChange}
          vsLastMonthLabel={d.vsLastMonth}
          icon={Car}
          iconColor="text-green-600"
          iconBg="bg-green-50"
        />
        {canViewRevenue ? (
          <StatCard
            title={d.kpiMonthlyRevenue}
            value={formatCurrency(kpis.monthlyRevenue, 'MAD')}
            change={kpis.revenueChange}
            vsLastMonthLabel={d.vsLastMonth}
            icon={DollarSign}
            iconColor="text-orange-600"
            iconBg="bg-orange-50"
          />
        ) : null}
        <StatCard
          title={d.kpiTotalCustomers}
          value={kpis.totalCustomers.toLocaleString()}
          change={kpis.customersChange}
          vsLastMonthLabel={d.vsLastMonth}
          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">{d.bookingSources}</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={d.barBookings} radius={[4, 4, 0, 0]} />
                <Bar dataKey="revenue" fill="#10b981" 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>

        {/* Quick stats */}
        <div className="card p-6">
          <h2 className="text-base font-semibold text-slate-900 mb-4">{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 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">{d.noData}</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">{d.recentReservations}</h2>
          <Link href="/reservations" className="text-sm text-blue-600 hover:text-blue-700 font-medium">
            {d.viewAll}
          </Link>
        </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">{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-slate-100">
              {(data?.recentReservations ?? []).map((res) => (
                <tr key={res.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-6 py-3">
                    <Link href={`/reservations/${res.id}`} className="text-sm font-medium text-blue-600 hover:text-blue-700">
                      #{res.bookingRef}
                    </Link>
                  </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">
                    {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-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">
                    {d.noReservations}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
