'use client';

import React, { useState, useEffect } from 'react';
import { getNearestSatsangs } from '@/lib/actions/nearest-satsang';
import { INearestSatsangsResponse } from '@/lib/types/nearest-satsang';
import { getCities, getAreas } from '@/lib/actions/geography';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { DateTime } from 'luxon';
import Link from 'next/link';

export default function NearestSatsangFinderPage() {
  const [coords, setCoords] = useState<{ lng: number; lat: number } | null>(null);
  const [geoStatus, setGeoStatus] = useState<'prompt' | 'loading' | 'success' | 'denied'>('prompt');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Search Results payload
  const [results, setResults] = useState<INearestSatsangsResponse | null>(null);

  // Fallback selectors
  const [cities, setCities] = useState<any[]>([]);
  const [areas, setAreas] = useState<any[]>([]);
  const [selectedCity, setSelectedCity] = useState('');
  const [selectedArea, setSelectedArea] = useState('');

  useEffect(() => {
    loadCities();
  }, []);

  const loadCities = async () => {
    try {
      const list = await getCities('');
      setCities(list);
    } catch (err) {
      console.error(err);
    }
  };

  const handleCityChange = async (cId: string) => {
    setSelectedCity(cId);
    setSelectedArea('');
    setAreas([]);
    if (cId) {
      const list = await getAreas(cId);
      setAreas(list);
      
      // Auto-trigger fallback search
      triggerFallbackSearch(cId, '');
    }
  };

  const handleAreaChange = (aId: string) => {
    setSelectedArea(aId);
    triggerFallbackSearch(selectedCity, aId);
  };

  // --- TRIGGER GEOLOCATION SEARCH ---

  const requestGeolocation = () => {
    if (!navigator.geolocation) {
      setGeoStatus('denied');
      setError('Browser Geolocation is not supported by your browser');
      return;
    }

    setGeoStatus('loading');
    setIsLoading(true);
    setError(null);

    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const lng = position.coords.longitude;
        const lat = position.coords.latitude;
        setCoords({ lng, lat });
        setGeoStatus('success');

        try {
          const res = await getNearestSatsangs(lng, lat);
          setResults(res);
        } catch (err: any) {
          setError(err.message || 'Failed to search nearby centers');
        } finally {
          setIsLoading(false);
        }
      },
      (err) => {
        setGeoStatus('denied');
        setIsLoading(false);
        // Do not throw/block, user can use fallback City select dropdowns
      }
    );
  };

  // --- TRIGGER MANUAL FALLBACK SEARCH ---

  const triggerFallbackSearch = async (cId: string, aId: string) => {
    setIsLoading(true);
    setError(null);
    setResults(null);
    setCoords(null);
    setGeoStatus('prompt');

    try {
      const res = await getNearestSatsangs(undefined, undefined, cId || undefined, aId || undefined);
      setResults(res);
    } catch (err: any) {
      setError(err.message || 'Manual fallback lookup failed');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6 max-w-4xl mx-auto">
      <div>
        <h1 className="text-2xl md:text-3xl font-bold text-gray-900 font-sans">Nearest Satsang Finder</h1>
        <p className="mt-1 text-sm text-gray-500">Find upcoming satsang check-ins or active centers near your current location.</p>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-800 p-4 rounded-xl text-sm font-semibold">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        {/* Left Search Sidebar controls */}
        <Card className="p-6 space-y-6 h-fit lg:col-span-1 border border-gray-150 shadow-sm">
          <div>
            <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider mb-3">Location Search</h3>
            <Button
              onClick={requestGeolocation}
              isLoading={isLoading && geoStatus === 'loading'}
              className="w-full justify-center bg-brand-primary text-white text-xs font-bold"
            >
              🧭 Use My Location
            </Button>
            <span className="text-[10px] text-gray-400 mt-1 block text-center">Requests browser coordinates session</span>
          </div>

          <div className="border-t border-gray-150 pt-4 space-y-4">
            <h3 className="text-xs font-bold text-gray-400 uppercase tracking-wider">Manual Location Fallback</h3>
            
            <div>
              <label className="block text-xs font-bold text-gray-500 mb-1">Select City</label>
              <select
                value={selectedCity}
                onChange={(e) => handleCityChange(e.target.value)}
                className="w-full rounded-lg border border-gray-250 p-2 bg-white text-xs"
              >
                <option value="">Choose City...</option>
                {cities.map((c) => <option key={c._id} value={c._id}>{c.name}</option>)}
              </select>
            </div>

            <div>
              <label className="block text-xs font-bold text-gray-500 mb-1">Select Area</label>
              <select
                value={selectedArea}
                onChange={(e) => handleAreaChange(e.target.value)}
                className="w-full rounded-lg border border-gray-250 p-2 bg-white text-xs"
                disabled={!selectedCity}
              >
                <option value="">Choose Area...</option>
                {areas.map((a) => <option key={a._id} value={a._id}>{a.name}</option>)}
              </select>
            </div>
          </div>
        </Card>

        {/* Right Search Results Panel */}
        <div className="lg:col-span-2 space-y-6">
          {isLoading && geoStatus !== 'loading' ? (
            <div className="text-center py-20 bg-white rounded-xl border border-gray-150 p-6 shadow-sm">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-primary mx-auto"></div>
              <p className="mt-2 text-xs text-gray-500 font-semibold">Searching nearby centers...</p>
            </div>
          ) : results ? (
            <div className="space-y-6">
              
              {/* Happening Soon Section */}
              <Card className="p-6">
                <h3 className="text-lg font-bold text-gray-900 border-b border-gray-150 pb-2 mb-4">
                  Happening Soon Near You
                </h3>

                {Object.values(results.happeningSoon).every(arr => arr.length === 0) ? (
                  <div className="text-center py-8 text-xs text-gray-400 font-semibold">
                    No active upcoming Satsang events found scheduled within radius.
                  </div>
                ) : (
                  <div className="space-y-6">
                    {['Today', 'Tomorrow', 'This Week', 'Later'].map((timeframe) => {
                      const list = results.happeningSoon[timeframe as keyof typeof results.happeningSoon] || [];
                      if (list.length === 0) return null;

                      return (
                        <div key={timeframe} className="space-y-3">
                          <h4 className="text-xs font-bold text-brand-primary uppercase tracking-widest flex items-center gap-1.5">
                            <span className="h-1.5 w-1.5 rounded-full bg-brand-primary"></span>
                            {timeframe}
                          </h4>
                          <div className="space-y-3">
                            {list.map((item) => (
                              <div key={item.satsang._id} className="p-4 border border-orange-100 rounded-xl bg-orange-50/5 flex justify-between items-center gap-4 shadow-sm">
                                <div>
                                  <h5 className="font-extrabold text-sm text-gray-950">{item.satsang.name}</h5>
                                  <span className="text-[10px] text-gray-500 font-bold block mt-1">
                                    {item.center.name} • {DateTime.fromISO(item.satsang.startDateTime).toFormat('hh:mm a')}
                                  </span>
                                </div>
                                <div className="text-right flex flex-col items-end gap-1.5">
                                  {item.distanceKm !== undefined && (
                                    <span className="text-xs font-black text-brand-primary">{item.distanceKm} km away</span>
                                  )}
                                  <div className="flex gap-2">
                                    {item.center.location?.coordinates && (
                                      <a
                                        href={`https://www.google.com/maps/dir/?api=1&destination=${item.center.location.coordinates[1]},${item.center.location.coordinates[0]}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="py-1 px-2.5 text-[10px] font-bold border rounded bg-white text-gray-600 hover:bg-gray-50"
                                      >
                                        Map Directions
                                      </a>
                                    )}
                                    <Link href={`/satsangs/${item.satsang._id}`} className="py-1 px-2.5 text-[10px] font-bold bg-brand-primary text-white rounded">
                                      Details
                                    </Link>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </Card>

              {/* Nearest Centers List */}
              <Card className="p-6">
                <h3 className="text-lg font-bold text-gray-900 border-b border-gray-150 pb-2 mb-4">
                  Nearest Satsang Centers
                </h3>

                {results.nearestCenters.length === 0 ? (
                  <div className="text-center py-8 text-xs text-gray-400 font-semibold">
                    No active centers mapped inside the configured radius limit.
                  </div>
                ) : (
                  <div className="divide-y divide-gray-100">
                    {results.nearestCenters.map((item) => (
                      <div key={item.center._id} className="py-3 flex justify-between items-center gap-4 text-xs">
                        <div>
                          <h5 className="font-extrabold text-gray-950">{item.center.name}</h5>
                          <p className="text-gray-500 mt-0.5 font-medium">{item.center.address}</p>
                          <span className="text-[10px] text-gray-400 font-bold block mt-1">
                            Schedule: {item.nextSatsang ? `Next Satsang ${DateTime.fromISO(item.nextSatsang.startDateTime).toFormat('dd LLL, hh:mm a')}` : 'No upcoming Satsang scheduled'}
                          </span>
                        </div>
                        <div className="text-right flex flex-col items-end gap-1.5 shrink-0">
                          {item.distanceKm !== undefined && (
                            <span className="font-black text-brand-primary text-xs">{item.distanceKm} km</span>
                          )}
                          {item.center.location?.coordinates && (
                            <a
                              href={`https://www.google.com/maps/dir/?api=1&destination=${item.center.location.coordinates[1]},${item.center.location.coordinates[0]}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="py-1 px-2.5 text-[9px] border rounded bg-white text-gray-500"
                            >
                              Directions
                            </a>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </Card>

            </div>
          ) : (
            <div className="text-center py-20 bg-white rounded-xl border border-gray-150 p-6 shadow-sm">
              <span className="text-3xl block">🧭</span>
              <h3 className="font-extrabold text-gray-900 mt-3 text-base">Coordinates Search Needed</h3>
              <p className="text-xs text-gray-400 mt-1 font-semibold">Click "Use My Location" or select fallback City selectors to begin.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
