'use client';

import { useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { MapPin, Loader2, CheckCircle2, AlertCircle, Pencil, Save, X } from 'lucide-react';

function ShareLocationContent() {
    const searchParams = useSearchParams();
    const phone = searchParams.get('phone') || undefined;
    const branch = searchParams.get('branch') || undefined;
    const token = searchParams.get('token') || undefined;

    const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
    const [isUpdating, setIsUpdating] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [errorMessage, setErrorMessage] = useState<string>('');
    const [address, setAddress] = useState<string>('');
    const [tempAddress, setTempAddress] = useState<string>('');

    const [isConfirmed, setIsConfirmed] = useState(false);

    const handleShareLocation = () => {
        setStatus('loading');
        setErrorMessage('');
        setIsConfirmed(false); // Reset confirmation on new location fetch

        if (!navigator.geolocation) {
            setStatus('error');
            setErrorMessage('Geolocation is not supported by your browser.');
            return;
        }

        navigator.geolocation.getCurrentPosition(
            async (position) => {
                try {
                    const { latitude, longitude } = position.coords;

                    const response = await fetch('/api/share-location', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            latitude,
                            longitude,
                            phone, // Sending phone from URL params
                            branch, // Sending branch from URL params
                            token, // Sending token from URL params
                            timestamp: new Date().toISOString(),
                            userAgent: navigator.userAgent,
                        }),
                    });

                    if (!response.ok) {
                        throw new Error('Failed to send location.');
                    }

                    const data = await response.json();
                    const receivedAddress = data.address || 'Address received, but format unknown.';
                    setAddress(receivedAddress);
                    setTempAddress(receivedAddress);
                    setStatus('success');
                } catch (error) {
                    console.error(error);
                    setStatus('error');
                    setErrorMessage('Failed to send location to the server.');
                }
            },
            (error) => {
                console.error(error);
                setStatus('error');
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        setErrorMessage('Location permission denied. Please enable it to continue.');
                        break;
                    case error.POSITION_UNAVAILABLE:
                        setErrorMessage('Location information is unavailable.');
                        break;
                    case error.TIMEOUT:
                        setErrorMessage('The request to get user location timed out.');
                        break;
                    default:
                        setErrorMessage('An unknown error occurred.');
                        break;
                }
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 0,
            }
        );
    };

    const handleUpdateAddress = () => {
        // Just update the local state, do not send to webhook yet.
        setAddress(tempAddress);
        setIsEditing(false);
        setIsConfirmed(false);
    };

    const handleConfirmAddress = async () => {
        setIsUpdating(true);
        try {
            const response = await fetch('/api/share-location', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    address: address,
                    type: 'confirmed',
                    phone,
                    branch,
                    token,
                    timestamp: new Date().toISOString(),
                }),
            });

            if (!response.ok) {
                throw new Error('Failed to confirm address.');
            }

            setIsConfirmed(true);
        } catch (error) {
            console.error(error);
            alert('Failed to confirm address. Please try again.');
        } finally {
            setIsUpdating(false);
        }
    };

    return (
        <main className="flex min-h-screen flex-col items-center justify-center p-4 text-white">
            <div className="relative group">
                {/* Glow effect */}
                <div className="absolute -inset-1 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 rounded-2xl blur opacity-25 group-hover:opacity-50 transition duration-1000 group-hover:duration-200"></div>

                <div className="relative px-8 py-10 bg-slate-950/50 backdrop-blur-xl ring-1 ring-white/10 rounded-xl leading-none flex flex-col items-center max-w-sm w-full transition-all duration-300">

                    <div className="mb-6 p-4 rounded-full bg-indigo-500/10 ring-1 ring-indigo-500/20 text-indigo-400">
                        <MapPin className="w-8 h-8" />
                    </div>

                    <h1 className="text-2xl font-bold tracking-tight bg-clip-text text-transparent bg-gradient-to-br from-white to-slate-400 mb-2">
                        Share Location
                    </h1>

                    <p className="text-slate-400 text-center text-sm mb-8 leading-relaxed">
                        Please allow access to your location to proceed.
                    </p>

                    {status === 'idle' && (
                        <button
                            onClick={handleShareLocation}
                            className="w-full py-3 px-6 rounded-lg bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white font-medium shadow-lg shadow-indigo-500/25 transition-all duration-200 hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center gap-2 cursor-pointer"
                        >
                            Allow Access
                        </button>
                    )}

                    {status === 'loading' && (
                        <button
                            disabled
                            className="w-full py-3 px-6 rounded-lg bg-slate-800 text-slate-400 font-medium cursor-not-allowed flex items-center justify-center gap-2"
                        >
                            <Loader2 className="w-4 h-4 animate-spin" />
                            Locating...
                        </button>
                    )}

                    {status === 'success' && (
                        <div className="w-full flex flex-col items-center gap-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
                            {!isEditing && !isConfirmed && (
                                <div className="w-full py-3 px-6 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 font-medium flex items-center justify-center gap-2">
                                    <CheckCircle2 className="w-5 h-5" />
                                    Location Found
                                </div>
                            )}

                            {isConfirmed && (
                                <div className="w-full py-3 px-6 rounded-lg bg-blue-500/10 text-blue-400 border border-blue-500/20 font-medium flex items-center justify-center gap-2">
                                    <CheckCircle2 className="w-5 h-5" />
                                    Address Confirmed
                                </div>
                            )}

                            {address && (
                                <div className="w-full p-4 rounded-lg bg-slate-900/50 border border-slate-800 relative group/address">
                                    <p className="text-xs text-slate-500 mb-2 uppercase tracking-wider font-semibold text-center">Location</p>

                                    {isEditing ? (
                                        <div className="flex flex-col gap-2">
                                            <p className="text-xs text-orange-400/80 text-center italic">
                                                Don't forget to add apartment/floor number if missing.
                                            </p>
                                            <textarea
                                                value={tempAddress}
                                                onChange={(e) => setTempAddress(e.target.value)}
                                                className="w-full bg-slate-800 border border-slate-700 rounded p-2 text-sm text-slate-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 min-h-[80px]"
                                            />
                                            <div className="flex gap-2 justify-end">
                                                <button
                                                    onClick={() => {
                                                        setIsEditing(false);
                                                        setTempAddress(address);
                                                    }}
                                                    className="p-2 rounded bg-slate-700 hover:bg-slate-600 text-slate-300 transition-colors cursor-pointer"
                                                    disabled={isUpdating}
                                                >
                                                    <X className="w-4 h-4" />
                                                </button>
                                                <button
                                                    onClick={handleUpdateAddress}
                                                    disabled={isUpdating}
                                                    className="p-2 rounded bg-indigo-600 hover:bg-indigo-500 text-white transition-colors flex items-center gap-2 cursor-pointer"
                                                >
                                                    {isUpdating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                                                    Update View
                                                </button>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="relative">
                                            <p className="text-sm text-slate-300 leading-snug text-center pr-6">
                                                {address}
                                            </p>
                                            {!isConfirmed && (
                                                <button
                                                    onClick={() => setIsEditing(true)}
                                                    className="absolute -top-1 -right-1 p-1.5 rounded-full hover:bg-slate-800 text-slate-500 hover:text-indigo-400 transition-colors cursor-pointer"
                                                    title="Edit Address"
                                                >
                                                    <Pencil className="w-3.5 h-3.5" />
                                                </button>
                                            )}
                                        </div>
                                    )}
                                </div>
                            )}

                            {!isEditing && !isConfirmed && address && (
                                <button
                                    onClick={handleConfirmAddress}
                                    disabled={isUpdating}
                                    className="w-full py-3 px-6 rounded-lg bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white font-medium shadow-lg shadow-emerald-500/25 transition-all duration-200 hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center gap-2 cursor-pointer"
                                >
                                    {isUpdating ? <Loader2 className="w-5 h-5 animate-spin" /> : <CheckCircle2 className="w-5 h-5" />}
                                    Confirm Address
                                </button>
                            )}
                        </div>
                    )}

                    {status === 'error' && (
                        <div className="w-full flex flex-col gap-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
                            <div className="py-3 px-4 rounded-lg bg-red-500/10 text-red-300 border border-red-500/20 font-medium flex gap-3 text-sm items-start">
                                <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                <div className="flex flex-col gap-1">
                                    <span className="font-semibold">Location Access Needed</span>
                                    <span className="opacity-90">{errorMessage}</span>
                                </div>
                            </div>

                            <div className="w-full p-4 rounded-lg bg-slate-900/50 border border-slate-800 flex flex-col gap-3">
                                <p className="text-sm text-slate-300">
                                    Alternatively, you can enter your address manually:
                                </p>
                                <textarea
                                    placeholder="Enter your full address (Street, Apt, City...)"
                                    value={tempAddress}
                                    onChange={(e) => setTempAddress(e.target.value)}
                                    className="w-full bg-slate-800 border border-slate-700 rounded p-3 text-sm text-slate-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 min-h-[100px]"
                                />
                                <button
                                    onClick={() => {
                                        if (!tempAddress.trim()) return;
                                        setAddress(tempAddress);
                                        // Directly confirm the manual entry
                                        setIsUpdating(true); // Re-use isUpdating for loading state here
                                        fetch('/api/share-location', {
                                            method: 'POST',
                                            headers: { 'Content-Type': 'application/json' },
                                            body: JSON.stringify({
                                                address: tempAddress,
                                                type: 'confirmed', // Treat manual entry as confirmed immediately
                                                phone,
                                                branch,
                                                token,
                                                timestamp: new Date().toISOString(),
                                            }),
                                        })
                                            .then(async (res) => {
                                                if (!res.ok) throw new Error('Failed');
                                                setStatus('success');
                                                setIsConfirmed(true);
                                            })
                                            .catch(() => alert('Failed to send address.'))
                                            .finally(() => setIsUpdating(false));
                                    }}
                                    disabled={!tempAddress.trim() || isUpdating}
                                    className="w-full py-2.5 rounded bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium transition-colors cursor-pointer flex items-center justify-center gap-2"
                                >
                                    {isUpdating ? <Loader2 className="w-4 h-4 animate-spin" /> : <span>Submit Address</span>}
                                </button>
                            </div>

                            <div className="flex justify-center">
                                <button
                                    onClick={handleShareLocation}
                                    className="text-xs text-slate-500 hover:text-slate-300 underline underline-offset-4 transition-colors cursor-pointer"
                                >
                                    Try Location Access Again
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </main>
    );
}

export default function ShareLocationPage() {
    return (
        <Suspense fallback={<div className="min-h-screen flex items-center justify-center text-white"><Loader2 className="w-8 h-8 animate-spin" /></div>}>
            <ShareLocationContent />
        </Suspense>
    );
}
