import * as React from 'react';
import { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { 
  LogOut, CreditCard, ShieldCheck, HelpCircle, ArrowRight, PlusCircle, Trash2, Tag, Cpu, CheckCircle2,
  ListFilter, Calendar, Filter
} from 'lucide-react';
import { TranslationSet, BizzDevice, TripHistory, Language } from '../types';
import LanguageSelector from './LanguageSelector';

interface DashboardProps {
  userEmail: string;
  userDisplayName: string;
  bizzDevices: BizzDevice[];
  setBizzDevices: React.Dispatch<React.SetStateAction<BizzDevice[]>>;
  tripHistory: TripHistory[];
  setTripHistory: React.Dispatch<React.SetStateAction<TripHistory[]>>;
  onSignOut: () => void;
  t: TranslationSet;
  currentLang: Language;
  onLanguageChange: (lang: Language) => void;
  onFAQOpen: () => void;
}

export default function Dashboard({
  userEmail,
  userDisplayName,
  bizzDevices,
  setBizzDevices,
  tripHistory,
  setTripHistory,
  onSignOut,
  t,
  currentLang,
  onLanguageChange,
  onFAQOpen,
}: DashboardProps) {
  const [activeTab, setActiveTab] = useState<'overview' | 'devices' | 'trips' | 'order'>('overview');

  // Order device state
  const [orderType, setOrderType] = useState<'transponder' | 'plate'>('transponder');
  const [orderPlateNumber, setOrderPlateNumber] = useState('');
  const [orderSuccessMessage, setOrderSuccessMessage] = useState('');

  // Trip Filtering States
  const [selectedVehicleFilter, setSelectedVehicleFilter] = useState<string>('ALL');
  const [selectedLocationFilter, setSelectedLocationFilter] = useState<string>('ALL');

  // Handle ordering of new device
  const handleOrderSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!orderPlateNumber.trim()) return;

    const bizzId = Math.random().toString(36).substring(2, 8).toUpperCase();
    const cleanPlate = orderPlateNumber.trim().toUpperCase();

    const newDevice: BizzDevice = {
      id: `b-${bizzId}`,
      number: orderType === 'transponder' ? `6007 ${Math.floor(1000 + Math.random() * 9000)} ${Math.floor(1000 + Math.random() * 9000)}` : `DK${bizzId}`,
      status: 'Active',
      type: orderType === 'transponder' ? 'Brobizz Transponder' : 'Number Plate Payment (Nummerpladebetaling)',
      vehicle: `Mazda 3 - ${cleanPlate}`,
      country: orderType === 'plate' ? 'Danmark (DK)' : undefined
    };

    setBizzDevices([newDevice, ...bizzDevices]);
    setOrderSuccessMessage(t.orderSuccess);
    setOrderPlateNumber('');

    setTimeout(() => {
      setOrderSuccessMessage('');
    }, 5000);
  };

  // Remove device agreement
  const handleRemoveDevice = (deviceId: string) => {
    if (confirm('Er du sikker på, at du vil slette eller deaktivere denne aftale?')) {
      setBizzDevices(bizzDevices.filter(dev => dev.id !== deviceId));
    }
  };

  // Extract unique vehicles and locations for filters
  const uniqueVehicles = Array.from(new Set(tripHistory.map(trip => trip.vehicle)));
  const uniqueLocations = Array.from(new Set(tripHistory.map(trip => trip.location.split(' ')[0])));

  // Filtered trips
  const filteredTrips = tripHistory.filter(trip => {
    const matchesVehicle = selectedVehicleFilter === 'ALL' || trip.vehicle === selectedVehicleFilter;
    const matchesLocation = selectedLocationFilter === 'ALL' || trip.location.includes(selectedLocationFilter);
    return matchesVehicle && matchesLocation;
  });

  // Calculate total price of current filtered trips
  const totalSpent = tripHistory.reduce((acc, curr) => acc + curr.amount, 0);

  // SVG Chart data points for expenses over the last 5 months
  // We'll render a stunning customized curved line chart directly using SVG
  const chartPoints = [
    { label: 'Jan', value: 80 },
    { label: 'Feb', value: 240 },
    { label: 'Mar', value: 140 },
    { label: 'Apr', value: 540 },
    { label: 'Maj', value: 390 },
    { label: 'Jun', value: totalSpent },
  ];

  const maxVal = Math.max(...chartPoints.map(p => p.value)) * 1.1;
  const svgWidth = 500;
  const svgHeight = 150;
  
  // Calculate coordinates
  const pointsString = chartPoints.map((p, idx) => {
    const x = (idx / (chartPoints.length - 1)) * (svgWidth - 60) + 30;
    const y = svgHeight - (p.value / maxVal) * (svgHeight - 40) - 20;
    return `${x},${y}`;
  }).join(' ');

  return (
    <div className="min-h-screen bg-[#f7f6f2] text-neutral-800 font-sans selection:bg-neutral-200">
      {/* Top dashboard menu */}
      <nav className="sticky top-0 z-40 bg-white border-b border-neutral-100 px-6 py-4">
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-6">
            {/* Brobizz logo */}
            <div className="flex items-center gap-2">
              <span className="font-display font-black text-2xl tracking-tighter text-[#00965e]">Brobizz</span>
              <span className="text-[10px] bg-emerald-50 text-emerald-700 border border-emerald-100 font-mono px-2 py-0.5 rounded-full font-bold uppercase">
                Selvbetjening
              </span>
            </div>

            {/* Menu tab items on Desktop */}
            <div className="hidden lg:flex items-center gap-1.5 text-sm font-medium">
              {[
                { id: 'overview', label: t.dashTabOverview },
                { id: 'devices', label: t.dashTabBizz },
                { id: 'trips', label: t.dashTabTrips },
                { id: 'order', label: t.dashTabOrder },
              ].map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`px-4 py-2 rounded-xl transition duration-150 ${
                    activeTab === tab.id
                      ? 'bg-neutral-900 text-white'
                      : 'text-neutral-500 hover:text-neutral-900 hover:bg-neutral-100'
                  }`}
                >
                  {tab.label}
                </button>
              ))}
            </div>
          </div>

          {/* User Controls and Language selector */}
          <div className="flex items-center gap-4">
            <button
              onClick={onFAQOpen}
              className="text-neutral-400 hover:text-neutral-900 p-1 rounded-full transition"
              title="Hjælp & FAQ"
            >
              <HelpCircle className="w-5 h-5" />
            </button>

            <LanguageSelector currentLang={currentLang} onLanguageChange={onLanguageChange} />

            <div className="h-8 w-px bg-neutral-200" />

            {/* Simulated Log ut dropdown trigger */}
            <div className="flex items-center gap-3">
              <div className="hidden sm:flex flex-col text-right">
                <span className="font-medium text-xs text-neutral-900">{userDisplayName}</span>
                <span className="text-[10px] text-neutral-400 font-mono truncate max-w-[150px]">{userEmail}</span>
              </div>
              <button
                onClick={onSignOut}
                className="flex items-center gap-2 text-xs font-semibold text-red-600 hover:text-red-700 bg-red-50 hover:bg-red-100 px-3 py-2 rounded-xl border border-red-100 transition-all duration-150"
              >
                <LogOut className="w-3.5 h-3.5" />
                <span className="hidden sm:inline">{t.dashSignOut}</span>
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* Floating navigation tabs for Mobile / Tablet support */}
      <div className="lg:hidden bg-white border-b border-neutral-200/50 p-2 flex overflow-x-auto gap-1">
        {[
          { id: 'overview', label: t.dashTabOverview },
          { id: 'devices', label: t.dashTabBizz },
          { id: 'trips', label: t.dashTabTrips },
          { id: 'order', label: t.dashTabOrder },
        ].map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id as any)}
            className={`flex-none px-4 py-2 text-xs font-semibold rounded-xl transition duration-150 ${
              activeTab === tab.id
                ? 'bg-neutral-900 text-white'
                : 'text-neutral-500 hover:text-neutral-900 hover:bg-neutral-50'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Main Panel Content Area */}
      <main className="max-w-7xl mx-auto px-6 py-8">
        <AnimatePresence mode="wait">
          {/* OVERVIEW CONTENT TAB */}
          {activeTab === 'overview' && (
            <motion.div
              key="overview"
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -15 }}
              transition={{ duration: 0.3 }}
              className="space-y-6"
            >
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h1 className="text-3xl font-display font-bold text-neutral-900 tracking-tight">
                    {t.dashWelcome}
                  </h1>
                  <p className="text-sm text-neutral-500 mt-1">
                    {t.dashCustID}: <span className="font-mono text-neutral-800 font-bold">10928302-DK</span>
                  </p>
                </div>
                <div className="inline-flex items-center gap-2 px-3  py-1.5 rounded-full bg-emerald-50 border border-emerald-100 text-emerald-800 text-xs font-semibold">
                  <ShieldCheck className="w-4 h-4" />
                  <span>Konto: {t.dashActiveStatus}</span>
                </div>
              </div>

              {/* Bento cards layout for fast stats */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {/* Total Expanses Card */}
                <div className="bg-white rounded-2xl border border-neutral-100 p-6 shadow-sm hover:shadow-md transition">
                  <span className="text-xs font-mono text-neutral-400 uppercase tracking-wider">{t.overviewExpenses}</span>
                  <div className="flex items-baseline gap-2 mt-2">
                    <span className="text-4xl font-display font-extrabold text-neutral-900">{totalSpent},00</span>
                    <span className="text-sm font-semibold text-neutral-500">DKK</span>
                  </div>
                  <div className="mt-4 inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-600 bg-emerald-50/50 px-2 py-0.5 rounded-md">
                    +12.4% vs. sidste måned
                  </div>
                </div>

                {/* Total Trips Year */}
                <div className="bg-white rounded-2xl border border-neutral-100 p-6 shadow-sm hover:shadow-md transition">
                  <span className="text-xs font-mono text-neutral-400 uppercase tracking-wider">{t.overviewTripsCount}</span>
                  <div className="flex items-baseline gap-2 mt-2">
                    <span className="text-4xl font-display font-extrabold text-neutral-900">{tripHistory.length}</span>
                    <span className="text-sm font-semibold text-neutral-500">passager</span>
                  </div>
                  <div className="mt-4 inline-flex items-center gap-1 text-[11px] font-semibold text-[#00965e]">
                    Alle scanninger aktive
                  </div>
                </div>

                {/* Combined Hardware Agreements overview */}
                <div className="bg-white rounded-2xl border border-neutral-100 p-6 shadow-sm hover:shadow-md transition sm:col-span-2 lg:col-span-1">
                  <span className="text-xs font-mono text-neutral-400 uppercase tracking-wider">Aftalesummering</span>
                  <div className="grid grid-cols-2 gap-4 mt-3">
                    <div>
                      <div className="text-2xl font-bold font-display text-neutral-900">
                        {bizzDevices.filter(d => d.type.includes('Transponder')).length}
                      </div>
                      <div className="text-[10px] text-neutral-400 font-mono uppercase tracking-wider mt-0.5">
                        {t.overviewActiveDevices}
                      </div>
                    </div>
                    <div>
                      <div className="text-2xl font-bold font-display text-neutral-900">
                        {bizzDevices.filter(d => d.type.includes('Plate')).length}
                      </div>
                      <div className="text-[10px] text-neutral-400 font-mono uppercase tracking-wider mt-0.5">
                        {t.overviewLicensePlates}
                      </div>
                    </div>
                  </div>
                  <button
                    onClick={() => setActiveTab('order')}
                    className="mt-4 w-full flex items-center justify-between text-xs font-semibold text-[#00965e] hover:text-[#007a4c] bg-emerald-50/40 hover:bg-emerald-50 p-2 rounded-xl transition duration-150 border border-emerald-100/50"
                  >
                    <span>Opret ny aftale</span>
                    <PlusCircle className="w-4 h-4" />
                  </button>
                </div>
              </div>

              {/* Chart & Activity Panels */}
              <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
                {/* SVG Spend Chart Area */}
                <div className="bg-white rounded-3xl border border-neutral-100 p-6 shadow-sm flex flex-col justify-between lg:col-span-3">
                  <div>
                    <h3 className="font-bold text-neutral-950 text-base leading-snug">{t.overviewAnalytics}</h3>
                    <p className="text-xs text-neutral-400 mt-0.5">Viser forbrugshistorik i DKK</p>
                  </div>

                  <div className="my-6 relative">
                    <svg viewBox={`0 0 ${svgWidth} ${svgHeight}`} className="w-full h-auto overflow-visible">
                      {/* Grid lines */}
                      <line x1="30" y1="20" x2={svgWidth - 30} y2="20" stroke="#f1f5f9" strokeWidth="1" strokeDasharray="3 3" />
                      <line x1="30" y1="65" x2={svgWidth - 30} y2="65" stroke="#f1f5f9" strokeWidth="1" strokeDasharray="3 3" />
                      <line x1="30" y1="110" x2={svgWidth - 30} y2="110" stroke="#f1f5f9" strokeWidth="1" strokeDasharray="3 3" />

                      {/* Line connector path */}
                      <path d={`M ${pointsString}`} fill="none" stroke="#00965e" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />

                      {/* Plot Circles & Tooltips */}
                      {chartPoints.map((p, idx) => {
                        const x = (idx / (chartPoints.length - 1)) * (svgWidth - 60) + 30;
                        const y = svgHeight - (p.value / maxVal) * (svgHeight - 40) - 20;
                        return (
                          <g key={idx} className="group cursor-pointer">
                            <circle cx={x} cy={y} r="5" fill="#FFFFFF" stroke="#00965e" strokeWidth="3" />
                            {/* Hover tooltip for stats */}
                            <circle cx={x} cy={y} r="12" fill="transparent" className="hover:fill-[#00965e]/5" />
                            <text x={x} y={y - 12} textAnchor="middle" className="text-[10px] font-extrabold font-mono text-neutral-900 bg-white opacity-0 group-hover:opacity-100 transition-opacity">
                              {p.value} DKK
                            </text>
                          </g>
                        );
                      })}
                    </svg>

                    <div className="flex justify-between px-6 border-t border-neutral-50/80 pt-2 text-[10px] font-mono text-neutral-400">
                      {chartPoints.map((p, idx) => (
                        <span key={idx}>{p.label}</span>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Recent Trip Activities List Panel */}
                <div className="bg-white rounded-3xl border border-neutral-100 p-6 shadow-sm lg:col-span-2 flex flex-col justify-between">
                  <div>
                    <h3 className="font-bold text-neutral-950 text-base leading-snug">{t.recentActivity}</h3>
                    <p className="text-xs text-neutral-400 mt-0.5">Seneste 3 registrerede bropassager</p>
                  </div>

                  <div className="divide-y divide-neutral-100 my-4 flex-1">
                    {tripHistory.slice(0, 3).map((trip) => (
                      <div key={trip.id} className="py-3.5 flex items-center justify-between text-xs">
                        <div className="space-y-1">
                          <div className="font-bold text-neutral-900">{trip.location}</div>
                          <div className="text-[10px] text-neutral-400 font-mono">
                            {trip.date} • {trip.time} • {trip.vehicle}
                          </div>
                        </div>
                        <div className="text-right">
                          <span className="font-bold text-neutral-900 font-mono">-{trip.amount},00</span>
                          <span className="text-[9px] text-neutral-400 block font-mono">DKK</span>
                        </div>
                      </div>
                    ))}
                  </div>

                  <button
                    onClick={() => setActiveTab('trips')}
                    className="w-full py-3 bg-neutral-50 hover:bg-neutral-100 rounded-xl text-xs font-semibold text-neutral-700 flex items-center justify-center gap-1.5 transition"
                  >
                    <span>Gå til fuld turoversigt</span>
                    <ArrowRight className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </motion.div>
          )}

          {/* MY DEVICES TAB */}
          {activeTab === 'devices' && (
            <motion.div
              key="devices"
              initial={{ opacity: 0, scale: 0.98 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="space-y-8"
            >
              {/* Transponders devices */}
              <div className="space-y-4">
                <div>
                  <h2 className="text-xl font-display font-bold text-neutral-900 tracking-tight">{t.bizzTitle}</h2>
                  <p className="text-xs text-neutral-500 mt-0.5">{t.bizzSub}</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {bizzDevices.filter(d => d.type.includes('Transponder')).length === 0 ? (
                    <div className="p-8 text-center bg-white border border-neutral-150 border-dashed rounded-2xl text-xs text-neutral-400">
                      Ingen aktive bizz transpondere fundet.
                    </div>
                  ) : (
                    bizzDevices.filter(d => d.type.includes('Transponder')).map((dev) => (
                      <div key={dev.id} className="bg-white border border-neutral-100 rounded-3xl p-6 shadow-xs flex flex-col justify-between">
                        <div className="flex items-start justify-between">
                          <div className="flex gap-3">
                            <div className="h-10 w-10 bg-emerald-50 border border-emerald-100 rounded-xl flex items-center justify-center text-emerald-600">
                              <Cpu className="w-5 h-5" />
                            </div>
                            <div>
                              <div className="text-xs font-mono text-neutral-400 tracking-wider">TRANSPONDER-NUMMER</div>
                              <span className="font-bold text-neutral-900 font-mono text-sm">{dev.number}</span>
                            </div>
                          </div>
                          <span className="px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-100 font-bold text-[10px]">
                            {t.dashActiveStatus}
                          </span>
                        </div>

                        <div className="border-t border-neutral-100/80 pt-4 mt-6 flex items-center justify-between text-xs">
                          <div className="space-y-0.5">
                            <div className="text-[10px] uppercase font-mono text-neutral-400">{t.bizzVehicle}</div>
                            <span className="font-semibold text-neutral-700">{dev.vehicle}</span>
                          </div>
                          <button
                            onClick={() => handleRemoveDevice(dev.id)}
                            className="p-2 text-neutral-400 hover:text-red-600 hover:bg-neutral-50 rounded-xl transition"
                            title="Slet transponder aftale"
                          >
                            <Trash2 className="w-4.5 h-4.5" />
                          </button>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>

              {/* Number plate agreements */}
              <div className="space-y-4">
                <div>
                  <h2 className="text-xl font-display font-bold text-neutral-900 tracking-tight">{t.plateTitle}</h2>
                  <p className="text-xs text-neutral-500 mt-0.5">{t.plateSub}</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {bizzDevices.filter(d => d.type.includes('Plate')).length === 0 ? (
                    <div className="p-8 text-center bg-white border border-neutral-150 border-dashed rounded-2xl text-xs text-neutral-400">
                      Ingen aktive nummerpladebetalinger fundet.
                    </div>
                  ) : (
                    bizzDevices.filter(d => d.type.includes('Plate')).map((dev) => (
                      <div key={dev.id} className="bg-white border border-neutral-100 rounded-3xl p-6 shadow-xs flex flex-col justify-between">
                        <div className="flex items-start justify-between">
                          <div className="flex gap-3">
                            <div className="h-10 w-10 bg-emerald-50 border border-emerald-100 rounded-xl flex items-center justify-center text-emerald-600">
                              <CreditCard className="w-5 h-5" />
                            </div>
                            <div>
                              <div className="text-xs font-mono text-neutral-400 tracking-wider">AFTALE-ID</div>
                              <span className="font-bold text-neutral-900 font-mono text-sm">{dev.number}</span>
                            </div>
                          </div>
                          <span className="px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-100 font-bold text-[10px]">
                            {t.dashActiveStatus}
                          </span>
                        </div>

                        <div className="border-t border-neutral-100/80 pt-4 mt-6 flex items-center justify-between text-xs">
                          <div className="space-y-0.5">
                            <div className="text-[10px] uppercase font-mono text-neutral-400">{t.bizzVehicle}</div>
                            <span className="font-semibold text-neutral-700">{dev.vehicle}</span>
                          </div>
                          <div className="flex items-center gap-2">
                            {dev.country && (
                              <div className="text-[10px] text-neutral-400 font-mono uppercase bg-neutral-50 border px-2 py-0.5 rounded-md">
                                {dev.country}
                              </div>
                            )}
                            <button
                              onClick={() => handleRemoveDevice(dev.id)}
                              className="p-2 text-neutral-400 hover:text-red-600 hover:bg-neutral-50 rounded-xl transition"
                              title="Annuller nummerpladebetaling"
                            >
                              <Trash2 className="w-4.5 h-4.5" />
                            </button>
                          </div>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>
            </motion.div>
          )}

          {/* TRIP HISTORY TAB */}
          {activeTab === 'trips' && (
            <motion.div
              key="trips"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="space-y-6"
            >
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h2 className="text-2xl font-display font-bold text-neutral-900 tracking-tight">{t.dashTabTrips}</h2>
                  <p className="text-xs text-neutral-500 mt-0.5">Historik over alle dine passager og automatiske betalinger.</p>
                </div>

                {/* Filter indicators bar */}
                <div className="flex flex-wrap items-center gap-3">
                  {/* Vehicle selection dropdown */}
                  <div className="relative flex items-center gap-1.5 text-xs font-semibold bg-white border border-neutral-200 py-2 px-3.5 rounded-full shadow-xs hover:border-neutral-300">
                    <ListFilter className="w-3.5 h-3.5 text-neutral-400" />
                    <select
                      value={selectedVehicleFilter}
                      onChange={(e) => setSelectedVehicleFilter(e.target.value)}
                      className="bg-transparent focus:outline-hidden font-bold pr-2 cursor-pointer text-neutral-700"
                    >
                      <option value="ALL">Køretøj: Alle</option>
                      {uniqueVehicles.map(veh => (
                        <option key={veh} value={veh}>{veh}</option>
                      ))}
                    </select>
                  </div>

                  {/* Bridge location selection filter */}
                  <div className="relative flex items-center gap-1.5 text-xs font-semibold bg-white border border-neutral-200 py-2 px-3.5 rounded-full shadow-xs hover:border-neutral-300">
                    <Filter className="w-3.5 h-3.5 text-neutral-400" />
                    <select
                      value={selectedLocationFilter}
                      onChange={(e) => setSelectedLocationFilter(e.target.value)}
                      className="bg-transparent focus:outline-hidden font-bold pr-2 cursor-pointer text-neutral-700"
                    >
                      <option value="ALL">Sted: Alle</option>
                      {uniqueLocations.map(loc => (
                        <option key={loc} value={loc}>{loc}</option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>

              {/* Table list block */}
              <div className="bg-white rounded-3xl border border-neutral-100 overflow-hidden shadow-sm">
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse">
                    <thead>
                      <tr className="border-b border-neutral-100 text-[10px] font-mono uppercase tracking-wider text-neutral-400 bg-neutral-50/50">
                        <th className="px-6 py-4 font-semibold">{t.tripDate}</th>
                        <th className="px-6 py-4 font-semibold">Tidspunkt</th>
                        <th className="px-6 py-4 font-semibold">Passage-Sted</th>
                        <th className="px-6 py-4 font-semibold">Aftaleenhed</th>
                        <th className="px-6 py-4 font-semibold">Bilnummerplade</th>
                        <th className="px-6 py-4 font-semibold text-right">{t.tripCost}</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-neutral-100 text-xs">
                      {filteredTrips.length === 0 ? (
                        <tr>
                          <td colSpan={6} className="px-6 py-12 text-center text-neutral-400 font-mono">
                            Ingen ture fundet for den valgte filtrering.
                          </td>
                        </tr>
                      ) : (
                        filteredTrips.map((trip) => (
                          <tr key={trip.id} className="hover:bg-neutral-50/50 transition duration-150">
                            <td className="px-6 py-4 font-medium text-neutral-900 font-mono flex items-center gap-2">
                              <Calendar className="w-3.5 h-3.5 text-neutral-300" />
                              <span>{trip.date}</span>
                            </td>
                            <td className="px-6 py-4 font-mono text-neutral-500">{trip.time}</td>
                            <td className="px-6 py-4 font-bold text-neutral-900">{trip.location}</td>
                            <td className="px-6 py-4 font-mono text-neutral-500">{trip.deviceUsed}</td>
                            <td className="px-6 py-4">
                              <span className="bg-neutral-50 border border-neutral-200 font-semibold px-2 py-1 rounded-md text-[10px] font-mono tracking-wide text-neutral-600">
                                {trip.vehicle}
                              </span>
                            </td>
                            <td className="px-6 py-4 text-right font-extrabold text-neutral-900 font-mono">
                              -{trip.amount},00 {trip.currency}
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </motion.div>
          )}

          {/* ORDER NEW AGREEMENTS TAB */}
          {activeTab === 'order' && (
            <motion.div
              key="order"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              className="max-w-2xl mx-auto space-y-6"
            >
              <div>
                <h2 className="text-2xl font-display font-bold text-neutral-900 tracking-tight">{t.orderTitle}</h2>
                <p className="text-xs text-neutral-500 mt-0.5">{t.orderSub}</p>
              </div>

              {orderSuccessMessage && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  className="p-4 bg-emerald-50 border border-emerald-200 rounded-2xl flex items-start gap-3.5 text-xs text-emerald-800"
                >
                  <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                  <div>
                    <strong className="block font-bold">Bestilling modtaget!</strong>
                    <span>{orderSuccessMessage}</span>
                  </div>
                </motion.div>
              )}

              <div className="bg-white border border-neutral-100 rounded-3xl p-6 md:p-8 shadow-sm">
                <form onSubmit={handleOrderSubmit} className="space-y-6">
                  {/* Choice between physically Transponder Box vs License Plate camera payment */}
                  <div className="space-y-2">
                    <label className="text-xs font-semibold text-neutral-600 uppercase tracking-widest font-mono">
                      {t.orderDeviceType}
                    </label>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {/* Transponder Card option */}
                      <div
                        onClick={() => setOrderType('transponder')}
                        className={`p-4 rounded-2xl border-2 text-left cursor-pointer transition-all duration-200 ${
                          orderType === 'transponder'
                            ? 'border-[#00965e] bg-emerald-50/10'
                            : 'border-neutral-200 hover:border-neutral-300'
                        }`}
                      >
                        <div className="flex items-center gap-2.5 font-bold text-sm text-neutral-900">
                          <Cpu className={`w-5 h-5 ${orderType === 'transponder' ? 'text-[#00965e]' : 'text-neutral-400'}`} />
                          <span>Brobizz transponder</span>
                        </div>
                        <p className="text-[11px] text-neutral-400 leading-relaxed mt-2">
                          {t.orderSelectTransponder}
                        </p>
                      </div>

                      {/* License Plate automatic scanner */}
                      <div
                        onClick={() => setOrderType('plate')}
                        className={`p-4 rounded-2xl border-2 text-left cursor-pointer transition-all duration-200 ${
                          orderType === 'plate'
                            ? 'border-[#00965e] bg-emerald-50/10'
                            : 'border-neutral-200 hover:border-neutral-300'
                        }`}
                      >
                        <div className="flex items-center gap-2.5 font-bold text-sm text-neutral-900">
                          <CreditCard className={`w-5 h-5 ${orderType === 'plate' ? 'text-[#00965e]' : 'text-neutral-400'}`} />
                          <span>Nummerpladebetaling</span>
                        </div>
                        <p className="text-[11px] text-neutral-400 leading-relaxed mt-2">
                          {t.orderSelectPlate}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* input license plate */}
                  <div className="space-y-2">
                    <label htmlFor="order-plate" className="block text-xs font-semibold text-neutral-600 uppercase tracking-widest font-mono">
                      {t.orderVehicleInput}*
                    </label>
                    <input
                      id="order-plate"
                      type="text"
                      required
                      value={orderPlateNumber}
                      onChange={(e) => setOrderPlateNumber(e.target.value.toUpperCase())}
                      placeholder="F.eks. DK AB 12 345"
                      className="w-full bg-neutral-50 border border-neutral-200 focus:border-neutral-900 rounded-xl px-4 py-3 text-sm outline-hidden transition font-mono tracking-wider"
                    />
                  </div>

                  <button
                    type="submit"
                    className="w-full bg-[#00965e] hover:bg-[#007a4c] text-white font-semibold py-3.5 rounded-xl text-sm flex items-center justify-center gap-2 transition shadow-md"
                  >
                    <span>{t.orderBtn}</span>
                    <ArrowRight className="w-4 h-4" />
                  </button>
                </form>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </main>
    </div>
  );
}
