import React, { useState, useEffect, useMemo } from 'react';
import { MapContainer, TileLayer, Marker, Popup, Polyline, useMap } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { 
  Phone, 
  MapPin, 
  Calendar, 
  ShieldAlert, 
  ChevronLeft, 
  LocateFixed, 
  Loader2,
  PhoneCall,
  Compass,
  Map as MapIcon,
  List
} from 'lucide-react';
import { useTranslation } from '../hooks/useTranslation';
import { useTheme } from '../hooks/useTheme';

interface UserInfo {
  id: string;
  name: string | null;
  phone: string | null;
}

interface ParticipantInfo {
  id: string;
  role: string;
  displayName: string | null;
  user: UserInfo | null;
}

interface LocationInfo {
  id: string;
  name: string;
  address: string | null;
  latitude: number;
  longitude: number;
  plannedStart: string | null;
  plannedEnd: string | null;
  status: string;
}

interface LegInfo {
  id: string;
  sequence: number;
  note: string | null;
  description: string | null;
  startDate: string | null;
  endDate: string | null;
  locations: LocationInfo[];
}

interface TourInfo {
  id: string;
  title: string;
  description: string | null;
  startDate: string | null;
  endDate: string | null;
  creator: UserInfo;
  participants: ParticipantInfo[];
  legs: LegInfo[];
}

interface ShareJourneyPageProps {
  token: string;
  onGoToHome: () => void;
}

// Component to dynamically recenter map to a location coordinate
const MapRecenter = ({ position }: { position: [number, number] | null }) => {
  const map = useMap();
  useEffect(() => {
    if (position) {
      map.setView(position, 15, { animate: true });
    }
  }, [position, map]);
  return null;
};

// Component to adjust bounds to fit all stop locations
const MapBoundsFit = ({ locations, trigger }: { locations: LocationInfo[]; trigger: number }) => {
  const map = useMap();
  useEffect(() => {
    if (locations.length > 0) {
      const bounds = L.latLngBounds(locations.map(l => [l.latitude, l.longitude]));
      if (locations.length === 1) {
        map.setView([locations[0].latitude, locations[0].longitude], 14, { animate: true });
      } else {
        map.fitBounds(bounds, { padding: [50, 50], maxZoom: 15 });
      }
    }
  }, [locations, trigger, map]);
  return null;
};

export const ShareJourneyPage: React.FC<ShareJourneyPageProps> = ({ token, onGoToHome }) => {
  const { t, lang, changeLanguage } = useTranslation();
  const { theme, changeTheme } = useTheme();

  const [tour, setTour] = useState<TourInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  const [focusedLocation, setFocusedLocation] = useState<[number, number] | null>(null);
  const [fitBoundsTrigger, setFitBoundsTrigger] = useState(0);
  const [activeTab, setActiveTab] = useState<'map' | 'itinerary'>('map');

  useEffect(() => {
    const queryParams = new URLSearchParams(window.location.search);
    const urlLang = queryParams.get('lang');
    const urlTheme = queryParams.get('theme');

    if (urlLang === 'vi' || urlLang === 'en' || urlLang === 'zh') {
      changeLanguage(urlLang as any);
    }
    if (urlTheme === 'light' || urlTheme === 'dark' || urlTheme === 'system') {
      changeTheme(urlTheme as any);
    }
  }, []);

  // Viewer's own GPS tracking
  const [userLocation, setUserLocation] = useState<[number, number] | null>(null);
  const [isLocating, setIsLocating] = useState(false);

  useEffect(() => {
    const fetchSharedTour = async () => {
      try {
        setLoading(true);
        const res = await fetch(`/api/v1/tours/share/${token}`);
        if (!res.ok) {
          throw new Error('Not found or disabled');
        }
        const data = await res.json();
        setTour(data.tour);
      } catch (err: any) {
        console.error(err);
        setError('expired_or_not_found');
      } finally {
        setLoading(false);
      }
    };
    if (token) {
      fetchSharedTour();
    }
  }, [token]);

  const allLocations = useMemo(() => {
    if (!tour) return [];
    const locs: LocationInfo[] = [];
    tour.legs.forEach(leg => {
      leg.locations.forEach(loc => {
        locs.push(loc);
      });
    });
    return locs;
  }, [tour]);

  const ownerContact = tour?.creator;
  const managerContacts = useMemo(() => {
    if (!tour) return [];
    return tour.participants
      .filter(p => p.role === 'MANAGER' && p.user)
      .map(p => ({
        name: p.displayName || p.user?.name || '',
        phone: p.user?.phone || ''
      }))
      .filter(c => c.phone);
  }, [tour]);

  const handleLocateMe = () => {
    if (!navigator.geolocation) {
      alert('Trình duyệt của bạn không hỗ trợ định vị.');
      return;
    }
    setIsLocating(true);
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const coords: [number, number] = [position.coords.latitude, position.coords.longitude];
        setUserLocation(coords);
        setFocusedLocation(coords);
        setIsLocating(false);
      },
      (err) => {
        console.error(err);
        setIsLocating(false);
        alert('Không thể lấy vị trí hiện tại. Vui lòng bật định vị GPS.');
      },
      { enableHighAccuracy: true }
    );
  };

  // Custom Map Markers
  const mapIcons = useMemo(() => {
    if (typeof window === 'undefined') return {};
    return {
      start: L.divIcon({
        className: '!bg-transparent !border-none',
        html: `<div class="w-8 h-8 bg-rose-600 rounded-full border-2 border-white shadow-xl flex items-center justify-center text-xs font-black text-white animate-in zoom-in duration-300">S</div>`,
        iconSize: [32, 32],
        iconAnchor: [16, 16]
      }),
      end: L.divIcon({
        className: '!bg-transparent !border-none',
        html: `<div class="w-8 h-8 bg-emerald-600 rounded-full border-2 border-white shadow-xl flex items-center justify-center text-xs font-black text-white animate-in zoom-in duration-300">E</div>`,
        iconSize: [32, 32],
        iconAnchor: [16, 16]
      }),
      visit: L.divIcon({
        className: '!bg-transparent !border-none',
        html: `<div class="w-6 h-6 bg-violet-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center"><div class="w-1.5 h-1.5 bg-white rounded-full opacity-60"></div></div>`,
        iconSize: [24, 24],
        iconAnchor: [12, 12]
      }),
      user: L.divIcon({
        className: '!bg-transparent !border-none',
        html: `
          <div class="relative flex items-center justify-center">
            <div class="absolute w-8 h-8 bg-blue-400 rounded-full opacity-35 animate-ping"></div>
            <div class="w-5 h-5 bg-blue-600 rounded-full border-2 border-white shadow-xl flex items-center justify-center z-10"></div>
          </div>
        `,
        iconSize: [32, 32],
        iconAnchor: [16, 16]
      })
    };
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-slate-50 dark:bg-slate-950 text-slate-800 dark:text-slate-100 transition-colors">
        <Loader2 className="w-12 h-12 text-rose-500 animate-spin mb-4" />
        <p className="font-bold text-sm">{t('loading')}</p>
      </div>
    );
  }

  if (error || !tour) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-slate-50 dark:bg-slate-950 text-slate-800 dark:text-slate-100 p-4 transition-colors">
        <div className="bg-[var(--surface)] dark:bg-slate-900 border border-[var(--border)] dark:border-slate-800 shadow-2xl rounded-[32px] p-8 max-w-md w-full text-center flex flex-col items-center gap-5">
          <div className="w-16 h-16 bg-rose-50 dark:bg-rose-950/20 border border-rose-100 dark:border-rose-900/30 rounded-full flex items-center justify-center text-rose-500">
            <ShieldAlert className="w-8 h-8" />
          </div>
          <h2 className="text-xl font-black tracking-tight">{t('error')}</h2>
          <p className="text-sm text-slate-500 dark:text-slate-400 leading-relaxed">
            {t('linkExpired')}
          </p>
          <button
            onClick={onGoToHome}
            className="w-full bg-slate-900 dark:bg-slate-100 hover:bg-slate-800 dark:hover:bg-white text-white dark:text-slate-900 font-bold py-3 px-6 rounded-2xl transition-all active:scale-95 text-sm"
          >
            {t('appName')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen w-screen flex flex-col bg-slate-50 dark:bg-slate-950 text-slate-800 dark:text-slate-100 transition-colors overflow-hidden">
      {/* Header */}
      <header className="h-16 shrink-0 bg-[var(--surface)]/70 dark:bg-slate-900/70 backdrop-blur-md border-b border-[var(--border)] dark:border-slate-800 px-4 md:px-6 flex items-center justify-between z-20">
        <div className="flex items-center gap-3">
          <button
            onClick={onGoToHome}
            className="p-2 hover:bg-[var(--background)] dark:hover:bg-slate-800 rounded-xl transition-all active:scale-95 text-[var(--text-muted)] dark:text-slate-400"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <div className="flex flex-col">
            <div className="flex items-center gap-2">
              <span className="w-2.5 h-2.5 bg-rose-500 rounded-full animate-pulse"></span>
              <h1 className="text-sm md:text-base font-black uppercase tracking-tight">{t('emergencyJourney')}</h1>
            </div>
            <p className="text-[10px] text-[var(--text-muted)] dark:text-slate-400 truncate max-w-[200px] sm:max-w-xs">{tour.title}</p>
          </div>
        </div>

        <div className="flex items-center gap-2 md:gap-3">
          {/* Language Selector */}
          <select
            value={lang}
            onChange={(e) => changeLanguage(e.target.value as any)}
            className="bg-[var(--background)] dark:bg-slate-800 border border-[var(--border)] dark:border-slate-700 text-[var(--text-primary)] dark:text-slate-100 rounded-xl px-2 py-1.5 text-xs font-bold focus:outline-none cursor-pointer"
          >
            <option value="vi">VI</option>
            <option value="en">EN</option>
            <option value="zh">ZH</option>
          </select>

          {/* Theme Selector */}
          <select
            value={theme}
            onChange={(e) => changeTheme(e.target.value as any)}
            className="bg-[var(--background)] dark:bg-slate-800 border border-[var(--border)] dark:border-slate-700 text-[var(--text-primary)] dark:text-slate-100 rounded-xl px-2 py-1.5 text-xs font-bold focus:outline-none cursor-pointer"
          >
            <option value="light">{t('themeLight')}</option>
            <option value="dark">{t('themeDark')}</option>
            <option value="system">{t('themeSystem')}</option>
          </select>
        </div>
      </header>

      {/* Mobile Tab Switcher */}
      <div className="lg:hidden h-12 shrink-0 bg-[var(--surface)] dark:bg-slate-900 border-b border-[var(--border)] dark:border-slate-800 flex items-center z-10 p-1">
        <button
          onClick={() => setActiveTab('map')}
          className={`flex-1 h-full flex items-center justify-center gap-2 text-xs font-bold rounded-lg transition-all ${activeTab === 'map' ? 'bg-rose-500 text-white shadow-md' : 'text-slate-500 dark:text-slate-400'}`}
        >
          <MapIcon className="w-4 h-4" />
          {t('viewMap')}
        </button>
        <button
          onClick={() => setActiveTab('itinerary')}
          className={`flex-1 h-full flex items-center justify-center gap-2 text-xs font-bold rounded-lg transition-all ${activeTab === 'itinerary' ? 'bg-rose-500 text-white shadow-md' : 'text-slate-500 dark:text-slate-400'}`}
        >
          <List className="w-4 h-4" />
          {t('viewTimeline')}
        </button>
      </div>

      {/* Main Layout Area */}
      <div className="flex-1 flex flex-col lg:grid lg:grid-cols-12 overflow-hidden">
        {/* Left Side Pane (Itinerary and Contacts) */}
        <div className={`flex-col lg:col-span-4 bg-[var(--surface)] dark:bg-slate-900 border-r border-[var(--border)] dark:border-slate-800 overflow-y-auto no-scrollbar ${activeTab === 'itinerary' ? 'flex h-full' : 'hidden lg:flex'}`}>
          <div className="p-4 md:p-6 space-y-6">
            {/* Tour Meta Info */}
            <div className="space-y-2">
              <h2 className="text-lg md:text-xl font-black text-[var(--text-primary)] dark:text-white leading-tight">{tour.title}</h2>
              {tour.startDate && (
                <div className="flex items-center gap-2 text-xs text-[var(--text-muted)] dark:text-slate-400">
                  <Calendar className="w-4 h-4 text-rose-500" />
                  <span>
                    {new Date(tour.startDate).toLocaleDateString()}
                    {tour.endDate && ` - ${new Date(tour.endDate).toLocaleDateString()}`}
                  </span>
                </div>
              )}
              {tour.description && (
                <p className="text-xs text-[var(--text-secondary)] dark:text-slate-400 leading-relaxed bg-[var(--background)] dark:bg-slate-950 p-3 rounded-2xl border border-[var(--border)] dark:border-slate-800/40">
                  {tour.description}
                </p>
              )}
            </div>

            {/* Emergency Contacts */}
            <div className="space-y-3">
              <h3 className="text-xs font-black text-rose-600 dark:text-rose-400 uppercase tracking-widest flex items-center gap-2">
                <Phone className="w-4 h-4" />
                {t('emergencyContacts')}
              </h3>

              <div className="space-y-3">
                {/* Creator/Owner contact */}
                {ownerContact && (
                  <div className="bg-rose-50/50 dark:bg-rose-950/10 border border-rose-100/50 dark:border-rose-950/20 p-4 rounded-2xl flex items-center justify-between gap-4">
                    <div className="min-w-0">
                      <div className="text-xs text-rose-600 dark:text-rose-400 font-bold uppercase tracking-wider">{t('tourOwner')}</div>
                      <div className="text-sm font-black text-[var(--text-primary)] dark:text-white truncate mt-0.5">{ownerContact.name || 'Anonymous'}</div>
                      <div className="text-xs text-[var(--text-muted)] dark:text-slate-400 mt-0.5">{ownerContact.phone || t('noPhone')}</div>
                    </div>
                    {ownerContact.phone && (
                      <a
                        href={`tel:${ownerContact.phone}`}
                        className="w-10 h-10 bg-rose-500 hover:bg-rose-600 text-white rounded-xl shadow-lg shadow-rose-500/20 flex items-center justify-center shrink-0 active:scale-95 transition-all"
                      >
                        <PhoneCall className="w-4 h-4" />
                      </a>
                    )}
                  </div>
                )}

                {/* Manager contacts */}
                {managerContacts.map((mgr, idx) => (
                  <div key={idx} className="bg-[var(--background)] dark:bg-slate-950 border border-[var(--border)] dark:border-slate-800 p-4 rounded-2xl flex items-center justify-between gap-4">
                    <div className="min-w-0">
                      <div className="text-xs text-[var(--text-muted)] dark:text-slate-400 font-bold uppercase tracking-wider">{t('tourManager')}</div>
                      <div className="text-sm font-black text-[var(--text-primary)] dark:text-white truncate mt-0.5">{mgr.name}</div>
                      <div className="text-xs text-[var(--text-muted)] dark:text-slate-400 mt-0.5">{mgr.phone}</div>
                    </div>
                    <a
                      href={`tel:${mgr.phone}`}
                      className="w-10 h-10 bg-slate-900 dark:bg-slate-100 hover:bg-slate-800 dark:hover:bg-white text-white dark:text-slate-900 rounded-xl shadow-md flex items-center justify-center shrink-0 active:scale-95 transition-all"
                    >
                      <PhoneCall className="w-4 h-4" />
                    </a>
                  </div>
                ))}

                {!ownerContact?.phone && managerContacts.length === 0 && (
                  <p className="text-xs text-[var(--text-muted)] dark:text-slate-500 italic">{t('noPhone')}</p>
                )}
              </div>
            </div>

            {/* Stops Hierarchy List */}
            <div className="space-y-3">
              <h3 className="text-xs font-black text-[var(--text-muted)] dark:text-slate-500 uppercase tracking-widest">
                {t('viewTimeline')}
              </h3>

              <div className="space-y-4 relative before:absolute before:left-3 before:top-2 before:bottom-2 before:w-[2px] before:bg-[var(--border)] dark:before:bg-slate-800">
                {allLocations.length === 0 ? (
                  <p className="text-xs text-[var(--text-muted)] dark:text-slate-500 italic pl-6">{t('noStops')}</p>
                ) : (
                  allLocations.map((loc, idx) => {
                    const isStart = idx === 0;
                    const isEnd = idx === allLocations.length - 1;
                    return (
                      <div
                        key={loc.id}
                        onClick={() => {
                          setFocusedLocation([loc.latitude, loc.longitude]);
                          // Auto switch to map tab on mobile when clicking a location
                          setActiveTab('map');
                        }}
                        className="group flex items-start gap-4 cursor-pointer pl-1 transition-all"
                      >
                        {/* Dot indicator */}
                        <div className="relative mt-1 shrink-0 z-10">
                          {isStart ? (
                            <div className="w-5 h-5 bg-rose-600 rounded-full border-4 border-white dark:border-slate-950 shadow-md flex items-center justify-center text-[8px] font-black text-white">S</div>
                          ) : isEnd ? (
                            <div className="w-5 h-5 bg-emerald-600 rounded-full border-4 border-white dark:border-slate-950 shadow-md flex items-center justify-center text-[8px] font-black text-white">E</div>
                          ) : (
                            <div className="w-4 h-4 bg-violet-600 rounded-full border-4 border-white dark:border-slate-950 shadow-sm ml-0.5"></div>
                          )}
                        </div>

                        {/* Details */}
                        <div className="flex-1 bg-[var(--background)]/50 hover:bg-[var(--background)] dark:bg-slate-950/40 dark:hover:bg-slate-950/80 p-3 rounded-2xl border border-[var(--border)]/50 dark:border-slate-800/40 transition-all select-none">
                          <h4 className="text-xs font-black text-[var(--text-primary)] dark:text-slate-200 group-hover:text-rose-500 dark:group-hover:text-rose-400 transition-colors">
                            {loc.name}
                          </h4>
                          {loc.address && (
                            <p className="text-[10px] text-[var(--text-muted)] dark:text-slate-400 truncate mt-0.5">{loc.address}</p>
                          )}
                          {loc.plannedStart && (
                            <p className="text-[9px] text-[var(--text-muted)] dark:text-slate-500 mt-1">
                              {new Date(loc.plannedStart).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                              {loc.plannedEnd && ` - ${new Date(loc.plannedEnd).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`}
                            </p>
                          )}
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Right Side Map Pane */}
        <div className={`relative flex-1 lg:col-span-8 h-full bg-[var(--background)] dark:bg-slate-950 ${activeTab === 'map' ? 'flex' : 'hidden lg:flex'}`}>
          {allLocations.length > 0 ? (
            <MapContainer
              center={[allLocations[0].latitude, allLocations[0].longitude]}
              zoom={13}
              preferCanvas={true}
              className="h-full w-full z-0"
              attributionControl={false}
            >
              <TileLayer
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                attribution=""
              />
              
              {/* Fit map bounds helper */}
              <MapBoundsFit locations={allLocations} trigger={fitBoundsTrigger} />

              {/* Recenter helper */}
              <MapRecenter position={focusedLocation} />

              {/* Polyline Route */}
              {allLocations.length > 1 && (
                <Polyline 
                  positions={allLocations.map(l => [l.latitude, l.longitude])} 
                  color="#ec4899" 
                  weight={4} 
                  dashArray="6, 12" 
                />
              )}

              {/* Location Stop Markers */}
              {allLocations.map((loc, idx) => {
                const isStart = idx === 0;
                const isEnd = idx === allLocations.length - 1;
                const markerIcon = isStart ? mapIcons.start : isEnd ? mapIcons.end : mapIcons.visit;

                return (
                  <Marker
                    key={loc.id}
                    position={[loc.latitude, loc.longitude]}
                    icon={markerIcon}
                  >
                    <Popup>
                      <div className="p-1">
                        <div className="font-black text-xs text-slate-900">{loc.name}</div>
                        {loc.address && <div className="text-[10px] text-[var(--text-muted)] mt-0.5">{loc.address}</div>}
                      </div>
                    </Popup>
                  </Marker>
                );
              })}

              {/* Viewer's GPS tracking marker */}
              {userLocation && (
                <Marker position={userLocation} icon={mapIcons.user}>
                  <Popup>
                    <div className="font-bold text-xs">{t('myCoords') || 'Vị trí của tôi'}</div>
                  </Popup>
                </Marker>
              )}
            </MapContainer>
          ) : (
            <div className="flex-1 flex flex-col items-center justify-center text-slate-400">
              <MapPin className="w-12 h-12 stroke-1 mb-2 animate-bounce" />
              <p className="text-xs">{t('noStops')}</p>
            </div>
          )}

          {/* Floating Actions on Map */}
          <div className="absolute bottom-6 right-6 z-[1000] flex flex-col gap-3">
            {/* Locate Me button */}
            <button
              onClick={handleLocateMe}
              className="w-12 h-12 bg-[var(--surface)] dark:bg-slate-900 border border-[var(--border)] dark:border-slate-800 rounded-2xl shadow-xl flex items-center justify-center text-[var(--text-secondary)] dark:text-slate-200 hover:bg-[var(--background)] dark:hover:bg-slate-800 transition-all active:scale-95"
              title="Định vị của tôi"
            >
              {isLocating ? (
                <Loader2 className="w-5 h-5 text-rose-500 animate-spin" />
              ) : (
                <LocateFixed className={`w-5 h-5 ${userLocation ? 'text-rose-500' : ''}`} />
              )}
            </button>

            {/* Fit bounds button */}
            {allLocations.length > 0 && (
              <button
                onClick={() => setFitBoundsTrigger(prev => prev + 1)}
                className="w-12 h-12 bg-[var(--surface)] dark:bg-slate-900 border border-[var(--border)] dark:border-slate-800 rounded-2xl shadow-xl flex items-center justify-center text-[var(--text-secondary)] dark:text-slate-200 hover:bg-[var(--background)] dark:hover:bg-slate-800 transition-all active:scale-95"
                title="Bao phủ toàn bộ"
              >
                <Compass className="w-5 h-5 text-violet-500" />
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
