'use client';

import React from 'react';
import { Station } from '@/types/stationTypes';
import { MapPin, Zap, Clock, ArrowLeft, ChevronRight } from 'lucide-react';

interface DesktopClusterDrawerProps {
  readonly stations: Station[] | null;
  readonly onClose: () => void;
  readonly onStationSelect: (station: Station) => void;
}

export function DesktopClusterDrawer({ stations, onClose, onStationSelect }: DesktopClusterDrawerProps) {
  const drawerRef = React.useRef<HTMLDivElement>(null);

  // Handle escape key
  React.useEffect(() => {
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [onClose]);

  // Handle click outside drawer
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (drawerRef.current && !drawerRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    // Add event listener after a short delay to avoid immediate trigger
    const timeoutId = setTimeout(() => {
      document.addEventListener('mousedown', handleClickOutside);
    }, 100);

    return () => {
      clearTimeout(timeoutId);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [onClose]);

  if (!stations || stations.length === 0) return null;

  // Get station availability summary
  const getStationSummary = (station: Station) => {
    const available = station.connectors.filter(c => c.status === 'Available').length;
    const total = station.connectors.length;
    const charging = station.connectors.filter(c => c.status === 'Charging').length;
    
    return { available, total, charging };
  };

  // Get status color for availability
  const getStatusColor = (available: number, charging: number) => {
    if (available > 0) return 'text-green-600';
    if (charging > 0) return 'text-yellow-600';
    return 'text-red-600';
  };

  // Get status background color
  const getStatusBgColor = (available: number, charging: number) => {
    if (available > 0) return 'bg-green-50 border-green-200';
    if (charging > 0) return 'bg-yellow-50 border-yellow-200';
    return 'bg-red-50 border-red-200';
  };

  return (
    <div 
      ref={drawerRef}
      className="fixed top-0 left-0 h-full w-96 bg-white shadow-2xl z-[9997] animate-slide-in-left overflow-y-auto"
    >
        <div className="flex flex-col h-full">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 bg-gray-50">
          <div className="flex items-center gap-3">
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-200 rounded-full transition-colors duration-200"
              title="Close cluster list"
            >
              <ArrowLeft className="w-5 h-5 text-gray-500" />
            </button>
            <h2 className="text-xl font-bold text-gray-900">Charging Stations</h2>
          </div>
          <span className="px-3 py-1 bg-blue-100 text-blue-800 text-sm font-medium rounded-full">
            {stations.length} {stations.length === 1 ? 'station' : 'stations'}
          </span>
        </div>

        {/* Content */}
        <div className="flex-1 p-4 space-y-3">
          {stations.map((station) => {
            const { available, total, charging } = getStationSummary(station);
            
            return (
              <button
                key={station.id}
                onClick={() => onStationSelect(station)}
                className="w-full p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-all duration-200 cursor-pointer hover:border-blue-300 group text-left"
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex-1 min-w-0">
                    <h3 className="text-lg font-semibold text-gray-900 group-hover:text-blue-600 transition-colors duration-200 truncate">
                      {station.name}
                    </h3>
                  </div>
                  <ChevronRight className="w-5 h-5 text-gray-400 group-hover:text-blue-500 transition-colors duration-200 flex-shrink-0" />
                </div>

                {/* Address */}
                <div className="flex items-start gap-2 text-sm text-gray-600 mb-3">
                  <MapPin className="w-4 h-4 mt-0.5 flex-shrink-0 text-gray-400" />
                  <span className="truncate">{station.address}, {station.city}</span>
                </div>

                {/* Availability Status */}
                <div className={`p-3 rounded-lg border ${getStatusBgColor(available, charging)}`}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <Zap className="w-4 h-4" />
                      <span className="text-sm font-medium text-gray-700">Availability</span>
                    </div>
                    <span className={`text-sm font-bold ${getStatusColor(available, charging)}`}>
                      {available}/{total}
                    </span>
                  </div>
                  
                  {charging > 0 && (
                    <div className="flex items-center gap-2 mt-2 pt-2 border-t border-current border-opacity-20">
                      <div className="w-2 h-2 bg-yellow-400 rounded-full animate-pulse"></div>
                      <span className="text-xs text-gray-600">{charging} in use</span>
                    </div>
                  )}
                </div>

                {/* Quick connector info */}
                <div className="mt-3 flex items-center gap-2 text-xs text-gray-500">
                  <span>{total} connector{total > 1 ? 's' : ''}</span>
                  <span>•</span>
                  <span>
                    {Math.max(...station.connectors.map(c => c.power))}kW max
                  </span>
                </div>
              </button>
            );
          })}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-gray-200 bg-gray-50">
          <div className="flex items-center justify-center gap-2 text-xs text-gray-400">
            <Clock className="w-3 h-3" />
            <span>Click any station for detailed information</span>
          </div>
        </div>
        </div>
    </div>
  );
}
