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

import React, { useState, useMemo } from 'react';
import { Booking, Property, Review } from '../types';
import { 
  Clock, 
  Calendar, 
  Car, 
  MapPin, 
  QrCode, 
  Trash2, 
  Ticket, 
  CheckCircle2, 
  AlertCircle, 
  RefreshCw, 
  Sparkles, 
  IndianRupee, 
  RotateCcw, 
  Filter, 
  Search,
  Check,
  TrendingDown,
  ExternalLink,
  Star,
  MessageSquare,
  Send,
  Zap
} from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';

interface MyBookingsPageProps {
  currentUser: { email: string; name: string };
  bookings: Booking[];
  properties: Property[];
  onCancelBooking: (booking: Booking) => void;
  onViewQrCode: (booking: Booking) => void;
  onSelectProperty: (propertyId: string) => void;
  onSubmitReview: (propertyId: string, bookingId: string, rating: number, comment: string) => void;
  onStartCharging?: (booking: Booking) => void;
}

export default function MyBookingsPage({
  currentUser,
  bookings,
  properties,
  onCancelBooking,
  onViewQrCode,
  onSelectProperty,
  onSubmitReview,
  onStartCharging
}: MyBookingsPageProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'completed' | 'cancelled'>('all');

  // Review states for completed visits
  const [reviewRatings, setReviewRatings] = useState<Record<string, number>>({});
  const [reviewComments, setReviewComments] = useState<Record<string, string>>({});
  const [reviewErrors, setReviewErrors] = useState<Record<string, string>>({});

  // Filter local user bookings
  const userBookings = useMemo(() => {
    return bookings.filter(b => b.userEmail === currentUser.email);
  }, [bookings, currentUser]);

  // Compute stats based on the driver's own booking list
  const pageStats = useMemo(() => {
    const active = userBookings.filter(b => b.status === 'Confirmed').length;
    const completed = userBookings.filter(b => b.status === 'Completed').length;
    const cancelled = userBookings.filter(b => b.status === 'Cancelled').length;
    
    // Sum of refunds completed or initiated
    const refundCapital = userBookings
      .filter(b => b.status === 'Cancelled')
      .reduce((sum, b) => sum + b.totalFare, 0);

    return { active, completed, cancelled, refundCapital };
  }, [userBookings]);

  // Dynamic filter lists
  const filteredBookings = useMemo(() => {
    return userBookings.filter(b => {
      // Search text matches title, vehicle plate, or passcode
      const text = searchQuery.toLowerCase().trim();
      const matchesText = text === '' || 
        b.propertyTitle.toLowerCase().includes(text) ||
        b.id.toLowerCase().includes(text) ||
        b.vehicleNumber.toLowerCase().includes(text);

      // Status matcher
      const matchesStatus = statusFilter === 'all' ||
        (statusFilter === 'active' && b.status === 'Confirmed') ||
        (statusFilter === 'completed' && b.status === 'Completed') ||
        (statusFilter === 'cancelled' && b.status === 'Cancelled');

      return matchesText && matchesStatus;
    });
  }, [userBookings, searchQuery, statusFilter]);

  // Help calculate the mock refund timestamp
  const getRefundTimestamp = (isoString: string) => {
    const d = new Date(isoString);
    d.setMinutes(d.getMinutes() + 12); // simulated cancellation processing delay
    return d.toLocaleTimeString('en-IN', { hour: 'numeric', minute: '2-digit', hour12: true });
  };

  const submitBookingFeedback = (bookingId: string, propertyId: string) => {
    const rating = reviewRatings[bookingId] || 5;
    const comment = reviewComments[bookingId] || '';

    if (!comment.trim()) {
      setReviewErrors(prev => ({ ...prev, [bookingId]: 'Feedback text comment cannot be empty.' }));
      return;
    }

    // Call upstream handler
    onSubmitReview(propertyId, bookingId, rating, comment);

    // Dynamic clean logs
    setReviewErrors(prev => ({ ...prev, [bookingId]: '' }));
    setReviewComments(prev => ({ ...prev, [bookingId]: '' }));
    // Feedback submitted alert
  };

  return (
    <div className="space-y-6">
      
      {/* ================= HERO METALINE & SUMMARY CARDS ================= */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 select-none">
        
        {/* Metric Card 1: Active Passes */}
        <div className="bg-slate-900 border border-slate-800 p-4 rounded-2xl flex items-center justify-between">
          <div>
            <span className="block text-[10px] text-slate-500 font-extrabold uppercase tracking-wide">Active Permits</span>
            <span className="text-xl font-extrabold text-amber-400 font-mono mt-1 block">
              {pageStats.active}
            </span>
          </div>
          <div className="p-2 bg-amber-500/10 text-amber-500 rounded-xl border border-amber-900/20">
            <Ticket className="w-5 h-5" />
          </div>
        </div>

        {/* Metric Card 2: Space Arrived */}
        <div className="bg-slate-900 border border-slate-800 p-4 rounded-2xl flex items-center justify-between">
          <div>
            <span className="block text-[10px] text-slate-500 font-extrabold uppercase tracking-wide">Checked In</span>
            <span className="text-xl font-extrabold text-emerald-400 font-mono mt-1 block">
              {pageStats.completed}
            </span>
          </div>
          <div className="p-2 bg-emerald-500/10 text-emerald-400 rounded-xl border border-emerald-900/20">
            <CheckCircle2 className="w-5 h-5" />
          </div>
        </div>

        {/* Metric Card 3: Canceled Slots */}
        <div className="bg-slate-900 border border-slate-800 p-4 rounded-2xl flex items-center justify-between">
          <div>
            <span className="block text-[10px] text-slate-500 font-extrabold uppercase tracking-wide font-mono">Cancelled Slots</span>
            <span className="text-xl font-extrabold text-rose-400 font-mono mt-1 block">
              {pageStats.cancelled}
            </span>
          </div>
          <div className="p-2 bg-rose-500/10 text-rose-400 rounded-xl border border-rose-900/20">
            <AlertCircle className="w-5 h-5" />
          </div>
        </div>

        {/* Metric Card 4: Refund Capital Saved */}
        <div className="bg-slate-900 border border-slate-800 p-4 rounded-2xl flex items-center justify-between">
          <div>
            <span className="block text-[10px] text-slate-500 font-extrabold uppercase tracking-wide">Refunds Compiled</span>
            <span className="text-xl font-extrabold text-indigo-400 font-mono mt-1 block flex items-center">
              <IndianRupee className="w-4 h-4 inline stroke-[2.5]" />
              {pageStats.refundCapital}
            </span>
          </div>
          <div className="p-2 bg-indigo-500/10 text-indigo-400 rounded-xl border border-indigo-900/20">
            <TrendingDown className="w-5 h-5" />
          </div>
        </div>

      </div>

      {/* ================= LOCAL SEARCH & TABS FILTER BAR ================= */}
      <div className="bg-slate-900 rounded-2xl p-4 border border-slate-800 flex flex-col md:flex-row gap-4 items-center justify-between">
        
        {/* Search Input bar */}
        <div className="relative w-full md:w-80">
          <Search className="absolute left-3.5 top-3 w-4 h-4 text-slate-500" />
          <input
            type="text"
            placeholder="Search by Station name, Passcode, Plate..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 placeholder-slate-600"
          />
          {searchQuery && (
            <button 
              onClick={() => setSearchQuery('')}
              className="absolute right-3 top-3 text-slate-500 hover:text-slate-300"
            >
              ✕
            </button>
          )}
        </div>

        {/* Filters Tabs switch */}
        <div className="flex gap-1.5 bg-slate-950 p-1 rounded-xl border border-slate-850 w-full md:w-auto overflow-x-auto">
          {[
            { key: 'all', label: 'All Booking Logs' },
            { key: 'active', label: 'Active Permits' },
            { key: 'completed', label: 'Checked In' },
            { key: 'cancelled', label: 'Cancelled Slots' }
          ].map((tab) => (
            <button
              key={tab.key}
              onClick={() => setStatusFilter(tab.key as any)}
              className={`flex-1 md:flex-initial px-3.5 py-1.5 rounded-lg text-[10px] md:text-xs font-bold transition-all whitespace-nowrap
                ${statusFilter === tab.key
                  ? 'bg-amber-500 text-slate-950 shadow-md font-extrabold'
                  : 'text-slate-400 hover:text-slate-250 hover:bg-slate-900'
                }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

      </div>

      {/* ================= RESERVATION LOGS SECTION ================= */}
      <div className="space-y-6">
        {filteredBookings.length === 0 ? (
          <div className="bg-slate-900 rounded-2xl p-12 text-center border border-slate-800 space-y-4">
            <div className="w-16 h-16 bg-slate-950 border border-slate-850 rounded-2xl flex items-center justify-center text-slate-500 mx-auto">
              <Ticket className="w-8 h-8 text-slate-650" />
            </div>
            <div>
              <h4 className="font-extrabold text-white text-base">No Matching Entries Found</h4>
              <p className="text-slate-500 text-xs mt-1 max-w-md mx-auto">
                No reservation matches your criteria. Try resetting the status tabs or reservation text search filters above.
              </p>
            </div>
            <button
              onClick={() => {
                setSearchQuery('');
                setStatusFilter('all');
              }}
              className="px-4 py-2 bg-slate-950 border border-slate-800 text-slate-350 rounded-xl hover:bg-slate-900 hover:text-white transition-all text-xs font-bold"
            >
              Clear All Filters
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            
            <AnimatePresence mode="popLayout">
              {filteredBookings.map((b) => {
                const isCancelled = b.status === 'Cancelled';
                const isCompleted = b.status === 'Completed';
                const isConfirmed = b.status === 'Confirmed';
                
                // Fine matching property details if any
                const targetProp = properties.find(p => p.id === b.propertyId);

                // Check if user has already submitted review for this booking
                const existingReview = targetProp?.reviews?.find(r => r.bookingId === b.id);

                return (
                  <motion.div
                    key={b.id}
                    layoutId={`booking-card-${b.id}`}
                    initial={{ opacity: 0, scale: 0.98, y: 10 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95, y: -10 }}
                    transition={{ duration: 0.25 }}
                    className={`relative overflow-hidden rounded-3xl border text-left transition-all flex flex-col justify-between
                      ${isCancelled 
                        ? 'bg-slate-955/30 border-slate-900 text-slate-550 opacity-85' 
                        : isCompleted
                          ? 'bg-slate-900 border-slate-800'
                          : 'bg-slate-900 border-slate-800 shadow-lg hover:shadow-xl hover:border-slate-700'
                      }`}
                  >
                    
                    {/* Visual Stamp Backing for status */}
                    {isCancelled && (
                      <div className="absolute top-2 right-2 border-2 border-dashed border-rose-500/20 text-rose-500/20 text-[10px] px-2 py-0.5 rounded font-black tracking-widest font-mono uppercase select-none rotate-6">
                        Cancelled Slot
                      </div>
                    )}
                    {isCompleted && (
                      <div className="absolute top-2 right-2 border-2 border-solid border-emerald-500/20 text-emerald-500/30 text-[10px] px-2 py-0.5 rounded font-black tracking-widest font-mono uppercase select-none -rotate-3">
                        Checked-In
                      </div>
                    )}

                    {/* Card Inner Padding */}
                    <div className="p-5 flex-1 flex flex-col justify-between gap-4">
                      
                      {/* Top Row: Brand Code and Tag */}
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <span className="font-mono text-[9px] bg-slate-950 border border-slate-850 px-2 py-0.8 rounded text-slate-400 font-bold uppercase tracking-widest">
                            PERMIT {b.id}
                          </span>
                          <span className={`text-[9px] px-2 py-0.5 rounded-full font-extrabold uppercase tracking-widest leading-none
                            ${isCancelled 
                              ? 'bg-rose-500/10 text-rose-400 border border-rose-500/10' 
                              : isCompleted 
                                ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/10' 
                                : 'bg-amber-500/10 text-amber-400 border border-amber-500/10 animate-pulse'
                            }`}
                          >
                            • {b.status}
                          </span>
                        </div>
                        
                        <div className="text-right">
                          <span className="text-[10px] text-slate-500 font-bold block">RESERVED AMOUNT</span>
                          <strong className={`text-base font-black font-mono flex items-center justify-end
                            ${isCancelled ? 'text-slate-500 line-through font-normal' : 'text-amber-400'}`}
                          >
                            <IndianRupee className="w-3.5 h-3.5 stroke-[2.5]" />
                            {b.totalFare}
                          </strong>
                        </div>
                      </div>

                      {/* Middle Details Box */}
                      <div className="space-y-3 pt-1">
                        <div>
                          <h4 className="font-extrabold text-sm text-white line-clamp-1">{b.propertyTitle}</h4>
                          <div className="flex items-center gap-1 text-[10px] text-slate-500 font-bold font-mono mt-0.5">
                            <MapPin className="w-3" />
                            <span>{targetProp ? `${targetProp.location.address}, ${targetProp.location.city}` : 'Bihar Local Reservation'}</span>
                          </div>
                        </div>

                        {/* Specs Grid */}
                        <div className="grid grid-cols-2 gap-2 bg-slate-950/70 border border-slate-850 p-2.5 rounded-xl text-[10px] font-mono text-slate-500 font-semibold">
                          <div className="space-y-1">
                            <div className="flex items-center gap-1.5">
                              <Calendar className="w-3.5 h-3.5 text-slate-500" />
                              <span className="text-slate-200 font-bold">{b.bookingDate}</span>
                            </div>
                            <div className="flex items-center gap-1.5">
                              <Clock className="w-3.5 h-3.5 text-slate-500" />
                              <span className="text-slate-200 truncate">{b.timeSlot}</span>
                            </div>
                          </div>

                          <div className="space-y-1 border-l border-slate-850 pl-2.5">
                            <div className="flex items-center gap-1.5">
                              <Car className="w-3.5 h-3.5 text-slate-500" />
                              <span className="text-amber-400 font-black uppercase tracking-tight truncate">{b.vehicleNumber}</span>
                            </div>
                            <div className="text-[9px] text-slate-500 font-bold">
                              {b.vehicleType} • {b.totalHours} hr block
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* Refund timeline tracker OR metadata log */}
                      {isCancelled ? (
                        <div className="p-3 bg-rose-950/20 border border-rose-900/30 rounded-xl space-y-2 text-[10px] leading-snug">
                          <div className="flex items-center justify-between text-rose-400 font-bold">
                            <span className="flex items-center gap-1">
                              <AlertCircle className="w-3.5 h-3.5" />
                              Cancellation Processed (₹{b.totalFare} Refunded)
                            </span>
                            <span className="text-[9px] font-bold font-mono bg-rose-950 text-rose-350 px-1 rounded border border-rose-900 border-opacity-30">
                              REFUNDED
                            </span>
                          </div>
                          
                          {/* Live simulated cancellation timestamps */}
                          <div className="text-slate-500 font-mono text-[9px] space-y-0.5">
                            <div>• Request timestamp: {new Date(b.createdAt).toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', dateStyle: 'short', timeStyle: 'short' })}</div>
                            <div>• Refund ledger sync: Completed at {getRefundTimestamp(b.createdAt)} via original payment source ({b.paymentMethod}).</div>
                          </div>
                        </div>
                      ) : (
                        <div className="p-3 bg-slate-950/45 border border-slate-850 rounded-xl flex items-center justify-between text-[10px] text-slate-500 font-mono">
                          <div>
                            <span className="block text-[8px] text-slate-500 font-bold uppercase">Transaction Type</span>
                            <span className="text-slate-455 font-bold">{b.paymentMethod === 'COD' ? 'Postpaid COD at Spot' : `Prepaid (${b.paymentMethod})`}</span>
                          </div>
                          <div className="text-right">
                            <span className="block text-[8px] text-slate-500 font-bold uppercase">Gate Status</span>
                            <span className={`font-black uppercase tracking-wide
                              ${isCompleted ? 'text-emerald-400 font-bold' : 'text-blue-400 animate-pulse'}`}
                            >
                              • {isCompleted ? 'Space Cleared & Locked' : 'Permit Active'}
                            </span>
                          </div>
                        </div>
                      )}

                      {/* ================= COMPLETED DRIVER RATINGS REVIEW FEEDBACK SYSTEM ================= */}
                      {isCompleted && (
                        <div className="border-t border-slate-850/80 pt-3.5 mt-1 space-y-3">
                          {existingReview ? (
                            <div className="p-3 bg-slate-950/60 border border-emerald-950/50 rounded-xl space-y-1">
                              <div className="flex items-center justify-between">
                                <span className="text-[9px] font-black text-emerald-400 flex items-center gap-1">
                                  <CheckCircle2 className="w-3.5 h-3.5" />
                                  YOUR FEEDBACK RECORDED
                                </span>
                                <div className="flex gap-0.5">
                                  {Array.from({ length: 5 }).map((_, i) => (
                                    <Star 
                                      key={i} 
                                      className={`w-3 h-3 ${i < existingReview.rating ? 'text-amber-400 fill-amber-400' : 'text-slate-800'}`} 
                                    />
                                  ))}
                                </div>
                              </div>
                              <p className="text-slate-400 text-[11px] font-sans font-medium italic">
                                "{existingReview.comment}"
                              </p>
                            </div>
                          ) : (
                            <div className="bg-slate-950/40 p-3 rounded-xl border border-slate-850/60 space-y-2.5">
                              <h5 className="text-[10px] font-extrabold text-amber-500 tracking-wide uppercase flex items-center gap-1">
                                <Star className="w-3.5 h-3.5 fill-amber-500 text-amber-500" />
                                <span>Rate your Visit experience</span>
                              </h5>

                              {/* Interactive Stars Selection row */}
                              <div className="flex gap-2.5 items-center">
                                <span className="text-[9.5px] text-slate-500 font-bold">Your Rating:</span>
                                <div className="flex gap-1.5">
                                  {Array.from({ length: 5 }).map((_, idx) => {
                                    const starsCount = idx + 1;
                                    const isLit = starsCount <= (reviewRatings[b.id] ?? 5);
                                    return (
                                      <button
                                        key={idx}
                                        type="button"
                                        onClick={() => setReviewRatings(prev => ({ ...prev, [b.id]: starsCount }))}
                                        className="transform hover:scale-120 transition-transform active:scale-95 text-slate-600 focus:outline-none"
                                      >
                                        <Star 
                                          className={`w-5 h-5 ${isLit ? 'text-amber-400 fill-amber-400' : 'text-slate-800'}`} 
                                        />
                                      </button>
                                    );
                                  })}
                                </div>
                                <span className="font-mono text-[10.5px] font-black text-amber-400">
                                  {reviewRatings[b.id] ?? 5}.0
                                </span>
                              </div>

                              {/* Comment box and Submit */}
                              <div className="space-y-1">
                                <textarea
                                  placeholder="Write a brief review... (charger speed, parking space, safety, wifi lounge)"
                                  value={reviewComments[b.id] || ''}
                                  onChange={(e) => setReviewComments(prev => ({ ...prev, [b.id]: e.target.value }))}
                                  className="w-full px-3 py-1.8 bg-slate-950 border border-slate-850 rounded-lg text-[11px] font-medium text-slate-200 outline-none focus:ring-1 focus:ring-amber-500 placeholder-slate-700 font-sans resize-none"
                                  rows={2}
                                />
                                
                                {reviewErrors[b.id] && (
                                  <p className="text-[9px] text-rose-455 font-bold font-mono">
                                    {reviewErrors[b.id]}
                                  </p>
                                )}

                                <button
                                  type="button"
                                  onClick={() => submitBookingFeedback(b.id, b.propertyId)}
                                  className="py-1 px-3.5 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg text-[10px] font-black font-sans transition-all flex items-center justify-center gap-1.5 focus:outline-none"
                                >
                                  <Send className="w-3" />
                                  <span>Submit Honest Review</span>
                                </button>
                              </div>
                            </div>
                          )}
                        </div>
                      )}

                    </div>

                    {/* Footer buttons row for Active permits (only if NOT cancelled) */}
                    {!isCancelled && (
                      <div className="bg-slate-950 px-5 py-3 border-t border-slate-850/60 flex items-center justify-between gap-2.5 shrink-0">
                        <button
                          type="button"
                          onClick={() => onSelectProperty(b.propertyId)}
                          className="px-2.5 py-1.5 bg-slate-900 hover:bg-slate-850 hover:text-white rounded-lg border border-slate-800 text-slate-400 hover:border-slate-700 text-[10px] font-bold tracking-tight transition-all flex items-center gap-1 font-mono"
                        >
                          <ExternalLink className="w-3.5 h-3.5" />
                          <span>Locate Hub Map</span>
                        </button>
                        
                        <div className="flex items-center gap-2">
                          {isConfirmed && (
                            <button
                              type="button"
                              onClick={() => onCancelBooking(b)}
                              className="px-2.5 py-1.5 bg-rose-955/10 text-rose-400 hover:text-white border border-rose-900 border-opacity-40 hover:bg-rose-600 rounded-lg text-[10px] font-black tracking-tight transition-all flex items-center gap-1 cursor-pointer"
                            >
                              <Trash2 className="w-3 h-3" />
                              <span>Cancel Slot</span>
                            </button>
                          )}

                          {isConfirmed && (b.propertyType === 'charging' || b.propertyType === 'both') && onStartCharging && (
                            <button
                              type="button"
                              onClick={() => onStartCharging(b)}
                              className="px-2.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-[10px] font-black tracking-tight transition-all flex items-center gap-1 cursor-pointer font-mono shadow-sm"
                            >
                              <Zap className="w-3.5 h-3.5 fill-none" />
                              <span>Plug In & Charge</span>
                            </button>
                          )}
                          
                          <button
                            type="button"
                            onClick={() => onViewQrCode(b)}
                            className={`px-3.5 py-1.5 rounded-lg text-[10px] font-black tracking-tight transition-all flex items-center gap-1 cursor-pointer font-mono
                              ${isCompleted
                                ? 'bg-slate-900 border border-slate-850 text-emerald-450 hover:text-emerald-350 hover:bg-slate-850'
                                : 'bg-amber-500 text-slate-950 hover:bg-amber-400'
                              }`}
                          >
                            <QrCode className="w-3.5 h-3.5" />
                            <span>{isCompleted ? 'Verified Stamp' : 'View Pass QR'}</span>
                          </button>
                        </div>
                      </div>
                    )}

                  </motion.div>
                );
              })}
            </AnimatePresence>

          </div>
        )}
      </div>

    </div>
  );
}
