/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { UserAccount, Booking } from '../types';
import { 
  User, 
  Mail, 
  Phone, 
  Car, 
  Wallet, 
  Sparkles, 
  Bookmark, 
  CheckCircle2, 
  Ticket, 
  ShieldCheck, 
  Save, 
  Edit3, 
  IndianRupee, 
  PlusCircle, 
  ArrowRight,
  TrendingUp,
  Award,
  CircleHelp
} from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';

interface ProfilePageProps {
  currentUser: UserAccount;
  onUpdateProfile: (updatedUser: UserAccount) => void;
  bookings: Booking[];
}

export default function ProfilePage({
  currentUser,
  onUpdateProfile,
  bookings
}: ProfilePageProps) {
  // Local edit states
  const [isEditing, setIsEditing] = useState(false);
  const [name, setName] = useState(currentUser.name);
  const [phone, setPhone] = useState(currentUser.phone || '+91 98765 43210');
  const [vehicleNo, setVehicleNo] = useState(currentUser.vehicleNo || 'MH12-FB-8899');
  const [vehicleModel, setVehicleModel] = useState(currentUser.vehicleModel || 'Tata Nexon EV Max');
  
  // Wallet simulator state
  const [topUpAmount, setTopUpAmount] = useState('');
  const [walletFeedback, setWalletFeedback] = useState('');

  // Statistics
  const userBookings = bookings.filter(b => b.userEmail === currentUser.email);
  const activeCount = userBookings.filter(b => b.status === 'Confirmed').length;
  const completedCount = currentUser.completedCheckins || userBookings.filter(b => b.status === 'Completed').length;
  const cancelledCount = userBookings.filter(b => b.status === 'Cancelled').length;
  
  const walletBalance = currentUser.walletBalance ?? 250;
  const nextDiscount = currentUser.nextDiscountPercent ?? 5;

  // Save changes
  const handleSaveProfile = (e: React.FormEvent) => {
    e.preventDefault();
    const updated = {
      ...currentUser,
      name,
      phone,
      vehicleNo: vehicleNo.toUpperCase(),
      vehicleModel
    };
    onUpdateProfile(updated);
    setIsEditing(false);
  };

  // Add Money simulator
  const handleTopUp = () => {
    const amt = parseFloat(topUpAmount);
    if (isNaN(amt) || amt <= 0) {
      setWalletFeedback('Please specify a valid top-up amount.');
      return;
    }
    const updated = {
      ...currentUser,
      walletBalance: walletBalance + amt
    };
    onUpdateProfile(updated);
    setTopUpAmount('');
    setWalletFeedback(`Successfully added ₹${amt} to your App Wallet!`);
    setTimeout(() => setWalletFeedback(''), 4000);
  };

  return (
    <div className="space-y-6 max-w-4xl mx-auto pb-12">
      
      {/* ================= PROFILE SMART CARD DISPLAY ================= */}
      <div className="relative overflow-hidden bg-gradient-to-br from-slate-900 via-slate-950 to-indigo-950 border border-slate-800 rounded-3xl p-6 md:p-8 shadow-2xl">
        
        {/* Background ambient circular glow */}
        <div className="absolute top-0 right-0 w-80 h-80 bg-amber-500/5 rounded-full blur-[80px]" />
        <div className="absolute -bottom-10 -left-10 w-60 h-60 bg-indigo-500/5 rounded-full blur-[60px]" />
        
        <div className="relative flex flex-col md:flex-row gap-6 items-center justify-between z-10">
          
          <div className="flex flex-col md:flex-row gap-5 items-center text-center md:text-left">
            
            {/* Elegant avatar shield with custom Charge Buddy logo */}
            <div className="relative">
              <div className="w-20 h-20 bg-slate-950 rounded-2xl border-2 border-amber-500 overflow-hidden flex items-center justify-center shadow-xl">
                <img 
                  src="/src/assets/images/charge_buddy_logo_1782140417233.jpg" 
                  alt="Charge Buddy Logo" 
                  className="w-full h-full object-cover"
                  referrerPolicy="no-referrer"
                />
              </div>
              <div className="absolute -bottom-1 -right-1 bg-emerald-500 text-slate-950 p-1.5 rounded-full border border-slate-950 shadow-md">
                <ShieldCheck className="w-3.5 h-3.5" />
              </div>
            </div>

            {/* Profile main credentials */}
            <div className="space-y-1">
              <div className="flex flex-col sm:flex-row sm:items-center gap-2">
                <h2 className="text-xl font-black text-white">{currentUser.name}</h2>
                <span className="inline-flex self-center px-2 py-0.5 bg-amber-500/10 border border-amber-500/20 text-amber-400 font-mono text-[9px] font-bold uppercase rounded-md">
                  DRIVER ID: {currentUser.id}
                </span>
              </div>
              <p className="text-xs text-slate-400 font-mono flex items-center justify-center md:justify-start gap-1">
                <Mail className="w-3.5 h-3.5 text-slate-500" />
                <span>{currentUser.email}</span>
              </p>
              <p className="text-xs text-slate-400 flex items-center justify-center md:justify-start gap-1">
                <Phone className="w-3.5 h-3.5 text-slate-500" />
                <span>{phone}</span>
              </p>
            </div>

          </div>

          {/* Quick-Stats floating widget */}
          <div className="bg-slate-900/80 border border-slate-800 p-4 rounded-2xl flex items-center gap-6 min-w-xs justify-around backdrop-blur-sm shadow-inner">
            <div className="text-center select-none">
              <span className="block text-[8px] text-slate-500 font-extrabold uppercase tracking-widest font-mono">Checked In</span>
              <span className="text-lg font-black text-emerald-400 font-mono">{completedCount}</span>
            </div>
            <div className="w-px h-8 bg-slate-800" />
            <div className="text-center select-none">
              <span className="block text-[8px] text-slate-500 font-extrabold uppercase tracking-widest font-mono">Cancelled</span>
              <span className="text-lg font-black text-slate-400 font-mono">{cancelledCount}</span>
            </div>
            <div className="w-px h-8 bg-slate-800" />
            <div className="text-center select-none">
              <span className="block text-[8px] text-slate-500 font-extrabold uppercase tracking-widest font-mono">My Wallet</span>
              <span className="text-lg font-black text-amber-400 font-mono flex items-center">
                <IndianRupee className="w-3.5 h-3.5" />
                {walletBalance}
              </span>
            </div>
          </div>

        </div>

      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        
        {/* ================= LEFT 2 COLUMNS: EDIT PROFILE OR INFO ================= */}
        <div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 md:col-span-2 space-y-6">
          
          <div className="flex items-center justify-between border-b border-slate-800 pb-4">
            <div className="flex items-center gap-1.5">
              <Award className="w-5 h-5 text-amber-500" />
              <h3 className="font-extrabold text-white text-sm">Driver Credentials & Vehicle Specs</h3>
            </div>
            
            <button
              onClick={() => setIsEditing(!isEditing)}
              className="px-3 py-1.5 rounded-xl border border-slate-850 hover:border-slate-750 text-slate-450 hover:text-white transition-all text-xs font-bold flex items-center gap-1.5"
            >
              {isEditing ? 'Discard' : (
                <>
                  <Edit3 className="w-3.5 h-3.5 text-amber-500" />
                  <span>Update Info</span>
                </>
              )}
            </button>
          </div>

          {isEditing ? (
            <form onSubmit={handleSaveProfile} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                
                <div className="space-y-1">
                  <label className="block text-[10px] text-slate-500 font-bold uppercase transition-all">FullName</label>
                  <input
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required
                    className="w-full px-4 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-slate-200 outline-none focus:ring-1 focus:ring-amber-500"
                  />
                </div>

                <div className="space-y-1">
                  <label className="block text-[10px] text-slate-500 font-bold uppercase">Mobile Number</label>
                  <input
                    type="text"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    required
                    className="w-full px-4 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-slate-200 outline-none focus:ring-1 focus:ring-amber-500"
                  />
                </div>

                <div className="space-y-1">
                  <label className="block text-[10px] text-slate-500 font-bold uppercase">Vehicle Plate NO</label>
                  <input
                    type="text"
                    value={vehicleNo}
                    onChange={(e) => setVehicleNo(e.target.value)}
                    required
                    placeholder="e.g. MH12AB1234"
                    className="w-full px-4 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-slate-200 outline-none focus:ring-1 focus:ring-amber-500"
                  />
                </div>

                <div className="space-y-1">
                  <label className="block text-[10px] text-slate-500 font-bold uppercase">Vehicle Car/Two-Wheeler Model</label>
                  <input
                    type="text"
                    value={vehicleModel}
                    onChange={(e) => setVehicleModel(e.target.value)}
                    required
                    placeholder="e.g. Tata Nexon EV"
                    className="w-full px-4 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-slate-200 outline-none focus:ring-1 focus:ring-amber-500"
                  />
                </div>

              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-amber-500 text-slate-950 font-black rounded-xl hover:bg-amber-400 transition-colors text-xs flex items-center justify-center gap-1.5 shadow-md mt-2"
              >
                <Save className="w-4 h-4" />
                <span>Save Profile Credentials</span>
              </button>
            </form>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              
              <div className="bg-slate-950 p-4 rounded-2xl border border-slate-850 space-y-1.5">
                <span className="block text-[9px] text-slate-500 font-extrabold uppercase tracking-wide">Registered Vehicle</span>
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-indigo-500/10 text-indigo-400 rounded-xl border border-indigo-900/10">
                    <Car className="w-5 h-5" />
                  </div>
                  <div>
                    <h4 className="font-extrabold text-xs text-white uppercase">{vehicleNo}</h4>
                    <p className="text-[10px] text-indigo-400 font-bold tracking-tight">{vehicleModel}</p>
                  </div>
                </div>
              </div>

              <div className="bg-slate-950 p-4 rounded-2xl border border-slate-850 space-y-1.5">
                <span className="block text-[9px] text-slate-500 font-extrabold uppercase tracking-wide">Auth Status</span>
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-emerald-500/10 text-emerald-400 rounded-xl border border-emerald-900/10">
                    <ShieldCheck className="w-5 h-5" />
                  </div>
                  <div>
                    <h4 className="font-extrabold text-xs text-emerald-400">ACTIVE COMPLIANT</h4>
                    <p className="text-[10px] text-slate-500 font-bold">Encrypted Gate-Pass Token Sync Enabled</p>
                  </div>
                </div>
              </div>

            </div>
          )}

          {/* ================= CURRENT SYSTEM STATUS / FAQ ================= */}
          <div className="bg-slate-950 border border-slate-850 rounded-2xl p-4 space-y-3">
            <h4 className="font-bold text-xs text-indigo-400 flex items-center gap-1 select-none">
              <CircleHelp className="w-4 h-4" />
              <span>How do the Rewards work?</span>
            </h4>
            <div className="text-[10px] text-slate-450 space-y-2 leading-relaxed font-mono">
              <p>1. <strong>Book a Hub</strong>: Search and reserve any high-speed EV charging port or parking slot slot.</p>
              <p>2. <strong>Successfully Visit & Check In</strong>: Show the encrypted Gate pass QR code to the station supervisor. Once they hit verify, your check-in registers.</p>
              <p>3. <strong>Collect Rewards</strong>: Instantly receive a <span className="text-amber-400 font-black font-sans">₹100 Cashback reward on your Wallet</span> + a <span className="text-emerald-400 font-black font-sans">5% OFF voucher promo</span> applied automatically to lower the fare on your next checkout booking!</p>
            </div>
          </div>

        </div>

        {/* ================= RIGHT COLUMN: WALLET SIMULATOR & SAVINGS ================= */}
        <div className="space-y-6">
          
          {/* WALLET DEPOSIT PANEL */}
          <div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 space-y-4">
            <div className="flex items-center gap-1.5 border-b border-slate-800 pb-3">
              <Wallet className="w-4.5 h-4.5 text-amber-500" />
              <h3 className="font-extrabold text-white text-sm">App Wallet Ledger</h3>
            </div>

            <div className="bg-slate-950 border border-slate-850 p-4 rounded-2xl text-center select-none">
              <span className="block text-[9px] text-slate-500 font-extrabold uppercase font-mono tracking-widest">Available Balance</span>
              <strong className="text-2xl font-black text-white font-mono flex items-center justify-center gap-1 mt-1 text-amber-500">
                <IndianRupee className="w-6 h-6 stroke-[3]" />
                {walletBalance}
              </strong>
            </div>

            {/* Simulated Top up input */}
            <div className="space-y-2">
              <span className="block text-[9px] text-slate-500 font-bold uppercase tracking-wider">Top Up Simulator (INR)</span>
              <div className="flex gap-2">
                <input
                  type="number"
                  placeholder="Enter amount (₹)"
                  value={topUpAmount}
                  onChange={(e) => setTopUpAmount(e.target.value)}
                  className="flex-1 px-3 py-1.5 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-slate-200 outline-none focus:ring-1 focus:ring-amber-500 placeholder-slate-700 font-mono"
                />
                <button
                  onClick={handleTopUp}
                  className="px-3 bg-amber-500 text-slate-950 font-black rounded-xl hover:bg-amber-400 transition-colors text-xs flex items-center justify-center gap-1 shadow"
                >
                  <PlusCircle className="w-4 h-4" />
                  <span>Deposit</span>
                </button>
              </div>
              
              {walletFeedback && (
                <p className="text-[10px] text-emerald-400 font-bold bg-emerald-950/40 p-2 border border-emerald-900/30 rounded-lg font-mono leading-tight">
                  {walletFeedback}
                </p>
              )}
            </div>
          </div>

          {/* ACTIVE REWARD VOUCHER BLOCK */}
          <div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 space-y-4">
            <div className="flex items-center gap-1.5 border-b border-slate-800 pb-3">
              <Sparkles className="w-4.5 h-4.5 text-amber-500" />
              <h3 className="font-extrabold text-white text-sm">Active Vouchers</h3>
            </div>

            {nextDiscount > 0 ? (
              <div className="bg-gradient-to-r from-amber-500 to-amber-600 rounded-2xl p-4 text-slate-950 relative overflow-hidden select-none shadow">
                
                {/* Visual tickets cutouts decor */}
                <div className="absolute top-1/2 -left-2 w-4 h-4 bg-slate-900 rounded-full transform -translate-y-1/2" />
                <div className="absolute top-1/2 -right-2 w-4 h-4 bg-slate-900 rounded-full transform -translate-y-1/2" />
                
                <div className="text-center space-y-1 relative z-10">
                  <span className="block text-[9px] font-black uppercase tracking-widest bg-slate-950 text-amber-400 px-2 py-0.5 rounded-md inline-block">COMPLETED CHECKIN BONUS</span>
                  <strong className="block text-2xl font-black leading-none pt-1">
                    {nextDiscount}% OFF COUPE
                  </strong>
                  <p className="text-[9.5px] font-bold opacity-90 leading-tight">Apply on your next EV Charging / Parking spot checkout.</p>
                </div>
              </div>
            ) : (
              <div className="text-center py-4 bg-slate-950 rounded-2xl border border-slate-850 text-slate-500 text-xs font-semibold">
                <Ticket className="w-8 h-8 text-slate-650 mx-auto mb-1.5 opacity-60" />
                <span>No promo vouchers active</span>
                <p className="text-[9px] text-slate-600 mt-1 max-w-xs mx-auto">Get checked-in by an EV supervisor once to unlock 5% off discounts!</p>
              </div>
            )}
          </div>

        </div>

      </div>

    </div>
  );
}
