
import React, { useRef, useState, useEffect } from 'react';
import { WizardState } from '../types';
import { UploadCloud, FileText, X, Image as ImageIcon, Sparkles, Loader2, MapPin, Navigation, Plus, Trash2, Flag, Target, AlertCircle, CheckCircle2, Car, Footprints } from 'lucide-react';
import { processFile } from '../utils/fileUtils';
import { getEnvVar } from '../utils/envUtils';

// --- HELPER COMPONENT: PLACE AUTOCOMPLETE INPUT (WIDGET VERSION) ---
interface PlaceAutocompleteInputProps {
    value: string;
    onChange: (val: string, preview?: string) => void;
    placeholder: string;
    icon: React.ReactNode;
    scriptLoaded: boolean;
    disabled?: boolean;
    onError?: (msg: string) => void;
    addressPreview?: string;
}

const PlaceAutocompleteInput: React.FC<PlaceAutocompleteInputProps> = ({ value, onChange, placeholder, icon, scriptLoaded, disabled, onError, addressPreview }) => {
    const inputRef = useRef<HTMLInputElement>(null);
    const autocompleteRef = useRef<any>(null);

    // Initialize Google Autocomplete Widget
    useEffect(() => {
        if (!scriptLoaded || !inputRef.current || !(window as any).google || autocompleteRef.current) return;

        try {
            const google = (window as any).google;
            
            // Use the standard Autocomplete widget attached to the input
            const autocomplete = new google.maps.places.Autocomplete(inputRef.current, {
                fields: ["place_id", "geometry", "name", "formatted_address"],
                types: ["geocode", "establishment"]
            });
            
            autocompleteRef.current = autocomplete;

            autocomplete.addListener("place_changed", () => {
                const place = autocomplete.getPlace();
                
                if (!place.geometry) {
                    return;
                }

                // FIX: Use formatted_address as fallback if name is empty/missing
                const name = place.name || place.formatted_address || "";
                const address = place.formatted_address;
                
                // Update parent state
                onChange(name, address);
            });
        } catch (e) {
            console.error("Autocomplete init error", e);
            if(onError) onError("Błąd inicjalizacji widgetu Google Maps.");
        }
    }, [scriptLoaded, onError, onChange]);

    return (
        <div className="relative w-full">
            <div className="absolute left-3 top-3.5 z-10 pointer-events-none">
                {icon}
            </div>
            <input 
                ref={inputRef}
                type="text"
                value={value}
                onChange={(e) => onChange(e.target.value)}
                disabled={disabled}
                className="w-full pl-9 p-3 border border-gray-300 rounded-md focus:border-[#EA4420] outline-none font-medium disabled:bg-gray-100 disabled:text-gray-400 transition-colors"
                placeholder={placeholder}
                autoComplete="off"
            />
            
            {/* Address Confirmation Hint */}
            {addressPreview && (
                <div className="text-[10px] text-gray-500 mt-1 ml-1 flex items-center gap-1 animate-fade-in">
                    <CheckCircle2 size={10} className="text-green-500" />
                    <span className="truncate">{addressPreview}</span>
                </div>
            )}
        </div>
    );
};


// --- MAIN COMPONENT ---
interface StepDetailsProps {
  data: WizardState;
  // Update Type Definition to allow functional updates
  updateData: (updates: Partial<WizardState> | ((prev: WizardState) => Partial<WizardState>)) => void;
  onGenerate: () => void;
  isGenerating: boolean;
}

const StepDetails: React.FC<StepDetailsProps> = ({ data, updateData, onGenerate, isGenerating }) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [error, setError] = useState<string | null>(null);
  
  // Specific Error State
  const [mapError, setMapError] = useState<{title: string, msg: string} | null>(null);
  const [scriptLoaded, setScriptLoaded] = useState(false);

  // --- HARDCODED FALLBACK KEY ---
  const AUTO_PASTE_KEY = 'AIzaSyAq9IgZswt5j7GGfH2s-ESenHmfvWFCFCg';

  const getEffectiveKey = () => {
    if (data.tripData?.googleMapsKey) return data.tripData.googleMapsKey;
    
    const viteKey = getEnvVar('VITE_GOOGLE_MAPS_KEY');
    if (viteKey) return viteKey;

    const procKey = getEnvVar('GOOGLE_MAPS_KEY');
    if (procKey) return procKey;

    return AUTO_PASTE_KEY;
  };

  const effectiveKey = getEffectiveKey();
  
  const isEnvKeyMissing = !getEnvVar('GOOGLE_MAPS_KEY') && 
                          !getEnvVar('VITE_GOOGLE_MAPS_KEY') &&
                          data.tripData?.googleMapsKey !== AUTO_PASTE_KEY;

  // --- GOOGLE MAPS LOADING ---
  const loadMapsScript = (apiKey: string) => {
      if (!apiKey) {
          setMapError({
              title: "Brak klucza API",
              msg: "System nie mógł znaleźć klucza. Skontaktuj się z administratorem."
          });
          return;
      }
      
      if ((window as any).google?.maps?.places) {
          setScriptLoaded(true);
          return;
      }
      
      const existingScript = document.querySelector(`script[src*="maps.googleapis.com/maps/api/js"]`);
      if (existingScript) {
          const interval = setInterval(() => {
              if ((window as any).google?.maps?.places) {
                  setScriptLoaded(true);
                  setMapError(null);
                  clearInterval(interval);
              }
          }, 500);
          return;
      }
      
      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&loading=async&v=weekly`;
      script.async = true;
      script.onload = () => {
          setTimeout(() => {
            if ((window as any).google?.maps?.places) {
                setScriptLoaded(true);
                setMapError(null);
            }
          }, 200);
      };
      script.onerror = () => {
          setMapError({ title: "Błąd sieci", msg: "Nie udało się pobrać skryptu Google Maps." });
      };
      document.head.appendChild(script);
  };

  useEffect(() => {
    if (data.eventType === 'trip') {
        (window as any).gm_authFailure = () => {
            setMapError({ title: "Klucz odrzucony przez Google", msg: "Podany klucz jest niepoprawny." });
            setScriptLoaded(false); 
        };
        if (effectiveKey) loadMapsScript(effectiveKey);
    }
  }, [data.eventType, effectiveKey]); 

  // Initialize Trip Data if missing
  useEffect(() => {
    if (data.eventType === 'trip') {
        if (!data.tripData) {
            updateData({
                tripData: {
                startPoint: { place: '', description: '' },
                endPoint: { place: '', description: '' },
                stops: [{ id: crypto.randomUUID(), place: '', description: '' }],
                travelMode: null, 
                googleMapsKey: AUTO_PASTE_KEY 
                }
            });
        } 
        else if (!data.tripData.googleMapsKey) {
            updateData(prev => ({
                tripData: { ...prev.tripData!, googleMapsKey: AUTO_PASTE_KEY }
            }));
        }
    }
  }, [data.eventType, updateData]); // Removed data.tripData dependency to avoid loops, handled by logic

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const newFiles = Array.from(e.target.files || []);
    if (newFiles.length === 0) return;
    if (data.files.length + newFiles.length > 3) {
      setError('Maksymalnie 3 pliki.');
      return;
    }
    setError(null);
    const processedFiles = await Promise.all(newFiles.map(processFile));
    updateData(prev => ({ files: [...prev.files, ...processedFiles] }));
  };

  const removeFile = (id: string) => {
    updateData(prev => ({ files: prev.files.filter(f => f.id !== id) }));
  };

  // --- TRIP DATA HELPERS (UPDATED TO USE FUNCTIONAL STATE UPDATES) ---
  const updateApiKey = (val: string) => {
      updateData(prev => ({
          tripData: prev.tripData ? { ...prev.tripData, googleMapsKey: val } : prev.tripData
      }));
      if (val.length > 10) setMapError(null);
  };

  const updatePoint = (pointType: 'startPoint' | 'endPoint', field: 'place' | 'description' | 'addressPreview', value: string) => {
      updateData(prev => {
          if (!prev.tripData) return {};
          return {
              tripData: {
                  ...prev.tripData,
                  [pointType]: {
                      ...prev.tripData[pointType],
                      [field]: value
                  }
              }
          };
      });
  };

  const updateStop = (id: string, field: 'place' | 'description' | 'addressPreview', value: string) => {
    updateData(prev => {
        if (!prev.tripData) return {};
        const newStops = prev.tripData.stops.map(s => s.id === id ? { ...s, [field]: value } : s);
        return {
            tripData: { ...prev.tripData, stops: newStops }
        };
    });
  };

  const addStop = () => {
    updateData(prev => {
        if (!prev.tripData) return {};
        return {
             tripData: {
                ...prev.tripData,
                stops: [...prev.tripData.stops, { id: crypto.randomUUID(), place: '', description: '' }]
            }
        };
    });
  };

  const removeStop = (id: string) => {
    updateData(prev => {
        if (!prev.tripData) return {};
        return {
            tripData: {
                ...prev.tripData,
                stops: prev.tripData.stops.filter(s => s.id !== id)
            }
        };
    });
  };

  const setTravelMode = (mode: 'DRIVING' | 'WALKING') => {
      updateData(prev => {
          if (!prev.tripData) return {};
          return {
              tripData: { ...prev.tripData, travelMode: mode }
          };
      });
  };

  // Validation Check
  const isTripModeValid = data.eventType !== 'trip' || (data.tripData && data.tripData.travelMode !== null);
  const isReadyToGenerate = data.title && isTripModeValid;

  return (
    <div className="space-y-10 animate-fade-in">
      <div>
        <h2 className="text-3xl font-bold tracking-tight text-gray-900 mb-3">Szczegóły</h2>
        <p className="text-gray-500 mb-8 text-lg">
          {data.eventType === 'trip' ? 'Zaplanuj trasę i opisz przebieg podróży.' : 'Uzupełnij informacje o wydarzeniu.'}
        </p>
      </div>

      <div className="space-y-8">
         
         {/* SEKCJA DLA WYCIECZEK (TRIP) */}
         {data.eventType === 'trip' && data.tripData && (
           <div className="bg-gray-50 border border-gray-200 rounded-xl p-6 space-y-6">
              
              {/* Fallback Input */}
              {(!data.tripData.googleMapsKey && isEnvKeyMissing) && (
                <div className="bg-yellow-50 p-4 rounded-md border border-yellow-200 mb-2">
                    <div className="flex items-start gap-3">
                        <AlertCircle className="text-yellow-600 mt-0.5" size={20} />
                        <div className="flex-1">
                            <h4 className="font-bold text-yellow-800 text-sm">Nie wykryto klucza w .env</h4>
                            <p className="text-xs text-yellow-700 mt-1 mb-2">
                                System automatycznie wklei klucz zapasowy. Jeśli to nie nastąpiło, wklej go poniżej.
                            </p>
                            <input 
                                type="text" 
                                value={data.tripData?.googleMapsKey || ''}
                                onChange={(e) => updateApiKey(e.target.value)}
                                placeholder="Wklej klucz Google Maps API (AIza...)"
                                className="w-full p-2 text-sm border border-yellow-300 rounded bg-white focus:border-[#EA4420] outline-none"
                            />
                        </div>
                    </div>
                </div>
              )}

              {/* Detailed Error Banner for Maps */}
              {mapError && (
                  <div className="bg-red-50 border border-red-200 p-4 rounded-lg flex items-start gap-3 text-red-700">
                      <AlertCircle className="flex-shrink-0 mt-0.5" size={20} />
                      <div className="text-sm">
                          <p className="font-bold text-red-800">{mapError.title}</p>
                          <p className="mt-1 leading-relaxed">{mapError.msg}</p>
                      </div>
                  </div>
              )}

              <div className="flex items-center justify-between gap-2 mb-2 pt-1">
                 <div className="flex items-center gap-2">
                    <Navigation className="text-[#EA4420]" size={24} />
                    <h3 className="text-xl font-bold text-gray-900">Plan Podróży</h3>
                    {scriptLoaded && !mapError && (
                        <span className="hidden sm:flex text-xs bg-green-100 text-green-700 px-2 py-1 rounded-full font-bold items-center gap-1">
                            <CheckCircle2 size={12} /> API OK
                        </span>
                    )}
                 </div>
              </div>
              
              {/* BIG TRAVEL MODE SELECTOR */}
              <div className="grid grid-cols-2 gap-4 w-full">
                  <button 
                      onClick={() => setTravelMode('DRIVING')}
                      className={`flex flex-col items-center justify-center p-6 rounded-lg border-2 transition-all ${
                          data.tripData.travelMode === 'DRIVING' 
                          ? 'border-[#EA4420] bg-[#EA4420]/5 text-[#EA4420] ring-1 ring-[#EA4420] shadow-sm' 
                          : 'border-gray-200 bg-white text-gray-600 hover:border-[#EA4420]/50 hover:bg-gray-50'
                      }`}
                  >
                      <Car size={32} className="mb-2" />
                      <span className="font-bold text-sm sm:text-base">Samochód / Droga</span>
                  </button>
                  <button 
                      onClick={() => setTravelMode('WALKING')}
                      className={`flex flex-col items-center justify-center p-6 rounded-lg border-2 transition-all ${
                          data.tripData.travelMode === 'WALKING' 
                          ? 'border-[#EA4420] bg-[#EA4420]/5 text-[#EA4420] ring-1 ring-[#EA4420] shadow-sm' 
                          : 'border-gray-200 bg-white text-gray-600 hover:border-[#EA4420]/50 hover:bg-gray-50'
                      }`}
                  >
                      <Footprints size={32} className="mb-2" />
                      <span className="font-bold text-sm sm:text-base">Pieszo / Szlak</span>
                  </button>
              </div>

              {/* Validation Message if missing */}
              {!data.tripData.travelMode && (
                  <p className="text-center text-xs text-red-500 font-bold animate-pulse">
                      * Wybór rodzaju trasy jest wymagany
                  </p>
              )}

              <div className="space-y-4 pt-2">
                
                {/* START POINT */}
                <div className="flex gap-3 items-start">
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div className="relative">
                            <PlaceAutocompleteInput
                                value={data.tripData.startPoint.place}
                                onChange={(val, preview) => {
                                    updatePoint('startPoint', 'place', val);
                                    if(preview) updatePoint('startPoint', 'addressPreview', preview);
                                }}
                                addressPreview={data.tripData.startPoint.addressPreview}
                                placeholder="Punkt Startowy (np. Kraków)"
                                icon={<Flag size={16} className="text-green-600" />}
                                scriptLoaded={scriptLoaded}
                                onError={(msg) => setMapError({title: "Błąd API Places", msg})}
                            />
                        </div>
                        <input 
                            type="text"
                            value={data.tripData.startPoint.description}
                            onChange={(e) => updatePoint('startPoint', 'description', e.target.value)}
                            className="w-full p-3 border border-gray-300 rounded-md focus:border-[#EA4420] outline-none"
                            placeholder="Opis startu (np. Zbiórka o 6:00)"
                        />
                    </div>
                    {/* Placeholder for alignment */}
                    <div className="w-[42px]"></div>
                </div>

                {/* STOPS */}
                {data.tripData.stops.map((stop, index) => (
                    <div key={stop.id} className="flex gap-3 items-start group">
                       <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
                          <div className="relative">
                             <PlaceAutocompleteInput
                                value={stop.place}
                                onChange={(val, preview) => {
                                    updateStop(stop.id, 'place', val);
                                    if(preview) updateStop(stop.id, 'addressPreview', preview);
                                }}
                                addressPreview={stop.addressPreview}
                                placeholder={`Przystanek ${index + 1}`}
                                icon={<MapPin size={16} className="text-blue-500" />}
                                scriptLoaded={scriptLoaded}
                                onError={(msg) => setMapError({title: "Błąd API Places", msg})}
                             />
                          </div>
                          <input 
                             type="text"
                             value={stop.description}
                             onChange={(e) => updateStop(stop.id, 'description', e.target.value)}
                             className="w-full p-3 border border-gray-200 rounded-md focus:border-[#EA4420] outline-none"
                             placeholder="Co tam robiliście?"
                          />
                       </div>
                       <button 
                         onClick={() => removeStop(stop.id)}
                         className="p-3 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-md transition-colors"
                         title="Usuń przystanek"
                       >
                         <Trash2 size={18} />
                       </button>
                    </div>
                ))}

                <div className="pl-1">
                    <button 
                        onClick={addStop}
                        className="flex items-center space-x-2 text-sm font-bold text-[#EA4420] hover:bg-[#EA4420]/5 px-4 py-2 rounded-md transition-colors"
                    >
                        <Plus size={16} />
                        <span>Dodaj przystanek</span>
                    </button>
                </div>

                {/* END POINT */}
                <div className="flex gap-3 items-start">
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div className="relative">
                            <PlaceAutocompleteInput
                                value={data.tripData.endPoint.place}
                                onChange={(val, preview) => {
                                    updatePoint('endPoint', 'place', val);
                                    if(preview) updatePoint('endPoint', 'addressPreview', preview);
                                }}
                                addressPreview={data.tripData.endPoint.addressPreview}
                                placeholder="Punkt Końcowy (np. Zakopane)"
                                icon={<Target size={16} className="text-red-600" />}
                                scriptLoaded={scriptLoaded}
                                onError={(msg) => setMapError({title: "Błąd API Places", msg})}
                            />
                        </div>
                        <input 
                            type="text"
                            value={data.tripData.endPoint.description}
                            onChange={(e) => updatePoint('endPoint', 'description', e.target.value)}
                            className="w-full p-3 border border-gray-300 rounded-md focus:border-[#EA4420] outline-none"
                            placeholder="Opis końca (np. Nareszcie piwo)"
                        />
                    </div>
                    {/* Placeholder for alignment */}
                    <div className="w-[42px]"></div>
                </div>

              </div>
           </div>
         )}

         {/* STANDARDOWE POLA */}
         <div className="space-y-6">
             <div>
                <label className="block text-sm font-bold text-gray-700 mb-2">Tytuł wydarzenia</label>
                <input 
                  type="text" 
                  value={data.title}
                  onChange={(e) => updateData({ title: e.target.value })}
                  className="w-full p-4 border border-gray-200 rounded-md focus:ring-1 focus:ring-[#EA4420] focus:border-[#EA4420] outline-none transition-all font-medium text-gray-900 placeholder-gray-300"
                  placeholder="np. Roadtrip po Bałkanach"
                />
             </div>

             <div>
                <label className="block text-sm font-bold text-gray-700 mb-2">Krótki opis / Notatki</label>
                <textarea
                  value={data.description}
                  onChange={(e) => updateData({ description: e.target.value })}
                  placeholder="Ogólny klimat, emocje, dodatkowe szczegóły, których nie ma w planie wycieczki..."
                  rows={4}
                  className="w-full border border-gray-200 rounded-md p-4 text-base text-gray-700 focus:ring-1 focus:ring-[#EA4420] focus:border-[#EA4420] outline-none resize-none placeholder-gray-300"
                />
             </div>

             {/* File Upload */}
             <div>
                <label className="block text-sm font-bold text-gray-700 mb-2">Materiały pomocnicze (Max 3)</label>
                <div 
                  className={`border-2 border-dashed rounded-md p-8 flex flex-col items-center justify-center text-center transition-all cursor-pointer group ${
                    error ? 'border-red-300 bg-red-50' : 'border-gray-200 hover:border-[#EA4420] hover:bg-[#EA4420]/5'
                  }`}
                  onClick={() => data.files.length < 3 && fileInputRef.current?.click()}
                >
                  <input 
                    type="file" 
                    ref={fileInputRef} 
                    onChange={handleFileChange} 
                    multiple
                    accept=".gpx,.pdf,image/*"
                    className="hidden" 
                  />
                  <UploadCloud size={32} className="text-gray-300 group-hover:text-[#EA4420] mb-3 transition-colors" />
                  <p className="text-gray-600 font-medium">Kliknij, aby dodać pliki</p>
                  <p className="text-gray-400 text-xs mt-1">GPX, PDF, JPG, PNG</p>
                </div>
                
                {error && <p className="text-red-500 text-sm mt-2">{error}</p>}

                {/* File List */}
                {data.files.length > 0 && (
                  <div className="mt-4 grid grid-cols-1 gap-3">
                    {data.files.map((file) => (
                      <div key={file.id} className="flex items-center justify-between bg-gray-50 border border-gray-200 p-3 rounded-md">
                        <div className="flex items-center space-x-3 overflow-hidden">
                           <div className="w-10 h-10 bg-white rounded border border-gray-200 flex items-center justify-center flex-shrink-0 text-gray-400">
                              {file.mimeType.includes('image') ? <ImageIcon size={20} /> : <FileText size={20} />}
                           </div>
                           <span className="text-sm font-medium text-gray-700 truncate">{file.file.name}</span>
                        </div>
                        <button 
                          onClick={() => removeFile(file.id)}
                          className="text-gray-400 hover:text-red-500 p-1"
                        >
                          <X size={18} />
                        </button>
                      </div>
                    ))}
                  </div>
                )}
             </div>
         </div>
      </div>

      <div className="pt-6">
        <button 
            onClick={onGenerate}
            disabled={isGenerating || !isReadyToGenerate}
            className="w-full flex items-center justify-center space-x-2 bg-[#EA4420] text-white px-8 py-4 rounded-md hover:bg-[#d63b1a] transition-all disabled:opacity-75 disabled:cursor-not-allowed font-bold text-lg shadow-sm hover:shadow-md"
        >
            {isGenerating ? (
            <>
                <Loader2 size={24} className="animate-spin" />
                <span>Generowanie Historii...</span>
            </>
            ) : (
            <>
                <Sparkles size={24} />
                <span>Generuj Relację</span>
            </>
            )}
        </button>
      </div>
    </div>
  );
};

export default StepDetails;
