'use client';

import { useState, useRef, useEffect } from 'react';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import { CaretLeft, CaretRight, House, Buildings, Tent, MapPin, Users, Bed, Toilet, CheckCircle, UploadSimple, ShieldCheck, WifiHigh, Car, SwimmingPool, Desktop, Moon, Plant, HouseLine, X, Farm, City, Plus, Minus } from '@phosphor-icons/react/dist/ssr';
import localFont from 'next/font/local';
import Image from 'next/image';

const figtree = localFont({
    src: [
        {
            path: '../../../public/Fonts/figtree/figtree.ttf',
        },
    ],
});

// Types for form data
interface FormData {
    propertyType: string;
    location: string;
    description: string;
    title: string;
    guests: number;
    bedrooms: number;
    beds: number;
    bathrooms: number;
    amenities: string[];
    safety: string[];
    photos: File[]; // heavily mocked for now
    instantApproval: boolean;
}

const PROPERTY_TYPES = [
    { id: 'shared_house', label: 'Shared House', icon: Users },
    { id: 'entire_house', label: 'Entire House', icon: House },
    { id: 'farmhouse', label: 'Farmhouse', icon: Farm },
    { id: 'guesthouse', label: 'Guesthouse', icon: HouseLine },
    { id: 'apartment', label: 'Apartment', icon: City },
    { id: 'cabin', label: 'Cabin', icon: Tent },
];

const AMENITIES_LIST = [
    { id: 'wifi', label: 'Wi-Fi', icon: WifiHigh },
    { id: 'parking', label: 'Free Parking', icon: Car },
    { id: 'pool', label: 'Pool', icon: SwimmingPool },
    { id: 'workspace', label: 'Workspace', icon: Desktop },
];

const SAFETY_LIST = [
    { id: 'smoke_alarm', label: 'Smoke Alarm', icon: ShieldCheck },
    { id: 'first_aid', label: 'First Aid Kit', icon: ShieldCheck },
    { id: 'fire_ext', label: 'Fire Extinguisher', icon: ShieldCheck },
];

export default function List() {
    const [step, setStep] = useState(0);
    const containerRef = useRef<HTMLDivElement>(null);
    const formRef = useRef<HTMLDivElement>(null);

    const [formData, setFormData] = useState<FormData>({
        propertyType: '',
        location: '',
        description: '',
        title: '',
        guests: 4,
        bedrooms: 2,
        beds: 2,
        bathrooms: 1.5,
        amenities: [],
        safety: [],
        photos: [],
        instantApproval: false,
    });

    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isSuccess, setIsSuccess] = useState(false);
    const [error, setError] = useState('');

    // Animation for step transitions
    useGSAP(() => {
        gsap.fromTo(formRef.current,
            { opacity: 0, x: 20 },
            { opacity: 1, x: 0, duration: 0.5, ease: 'power2.out' }
        );
    }, [step]);

    const handleNext = () => {
        if (step === 5 && formData.photos.length < 5) {
            setError('Please upload at least 5 photos to continue.');
            return;
        }
        setError('');
        setStep((prev) => prev + 1);
    };

    const handleBack = () => {
        setStep((prev) => Math.max(0, prev - 1));
    };

    const handleChange = (field: keyof FormData, value: any) => {
        setFormData((prev) => ({ ...prev, [field]: value }));
    };

    const toggleArrayItem = (field: 'amenities' | 'safety', item: string) => {
        setFormData((prev) => {
            const list = prev[field];
            return list.includes(item)
                ? { ...prev, [field]: list.filter((i) => i !== item) }
                : { ...prev, [field]: [...list, item] };
        });
    };

    const handleSubmit = () => {
        setIsSubmitting(true);
        // Simulate API call
        setTimeout(() => {
            setIsSubmitting(false);
            setIsSuccess(true);
        }, 2000);
    };

    // Render Steps
    const renderStep = () => {
        if (isSuccess) {
            return (
                <div className="flex flex-col items-center justify-center h-full text-center space-y-6 animate-in fade-in zoom-in duration-500">
                    <CheckCircle className="w-24 h-24 text-[#E7FE78] fill-current" weight="fill" />
                    <h2 className={`${figtree.className} text-3xl font-bold`}>Submission Received!</h2>
                    <p className={`${figtree.className} text-xl text-gray-600 max-w-md`}>
                        We are processing your request, your listing will be manually reviewed before going live, this can take upto 24 hours.
                    </p>
                    <button
                        onClick={() => window.location.href = '/'}
                        className={`${figtree.className} mt-8 bg-[#E7FE78] text-black border-2 border-black shadow-[4px_4px_0px_rgba(0,0,0,1)] px-8 py-3 rounded-full hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-[2px_2px_0px_rgba(0,0,0,1)] transition-all active:shadow-none active:translate-x-[4px] active:translate-y-[4px]`}
                    >
                        Return Home
                    </button>
                </div>
            );
        }

        switch (step) {
            case 0: // Property Type
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>What kind of place will you host?</h2>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            {PROPERTY_TYPES.map((type) => {
                                const Icon = type.icon;
                                const isSelected = formData.propertyType === type.id;
                                return (
                                    <div
                                        key={type.id}
                                        onClick={() => handleChange('propertyType', type.id)}
                                        className={`cursor-pointer p-6 border-2 rounded-xl flex flex-col items-center space-y-4 transition-all duration-300 ${isSelected ? 'border-black bg-[#E7FE78] shadow-[4px_4px_0px_rgba(0,0,0,1)]' : 'border-gray-200 hover:border-black'
                                            }`}
                                    >
                                        <Icon className="w-12 h-12" />
                                        <span className={`${figtree.className} font-semibold text-lg`}>{type.label}</span>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                );
            case 1: // Location
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>Where's your place located?</h2>
                        <div className="space-y-4">
                            <label className={`${figtree.className} text-gray-600`}>Address</label>
                            <div className="relative">
                                <MapPin className="absolute left-4 top-1/2 -translate-y-1/2 w-6 h-6 text-gray-400" />
                                <input
                                    type="text"
                                    value={formData.location}
                                    onChange={(e) => handleChange('location', e.target.value)}
                                    placeholder="123 Lakeview Drive, Lakeside, CA"
                                    className={`${figtree.className} w-full pl-12 pr-4 py-4 border-2 border-gray-200 rounded-xl focus:border-black focus:outline-none transition-colors text-lg`}
                                />
                            </div>
                        </div>
                    </div>
                );
            case 2: // Basics (Capacity)
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>Share some basics about your place</h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {[
                                { label: 'Guests', field: 'guests', icon: Users },
                                { label: 'Bedrooms', field: 'bedrooms', icon: Moon },
                                { label: 'Beds', field: 'beds', icon: Bed },
                                { label: 'Bathrooms', field: 'bathrooms', icon: Toilet },
                            ].map((item) => {
                                const Icon = item.icon;
                                return (
                                    <div key={item.field} className="flex items-center justify-between p-4 border-2 border-gray-200 rounded-xl">
                                        <div className="flex items-center space-x-3">
                                            <Icon className="w-6 h-6 text-gray-500" />
                                            <span className={`${figtree.className} text-lg`}>{item.label}</span>
                                        </div>
                                        <div className="flex items-center space-x-4">
                                            <button
                                                onClick={() => handleChange(item.field as keyof FormData, Math.max(0, (formData[item.field as keyof FormData] as number) - 1))}
                                                className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:border-black transition-colors cursor-pointer hover:bg-[#E7FE78] hover:border-2"
                                            >
                                                <Minus />   
                                            </button>
                                            <span className={`${figtree.className} text-xl w-6 text-center`}>{formData[item.field as keyof FormData] as number}</span>
                                            <button
                                                onClick={() => handleChange(item.field as keyof FormData, (formData[item.field as keyof FormData] as number) + 1)}
                                                className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:border-black transition-colors cursor-pointer hover:bg-[#E7FE78] hover:border-2"
                                            >
                                                <Plus />
                                            </button>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                );
            case 3: // Description
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>Describe your place</h2>
                        <div className="space-y-4">
                            <div>
                                <label className={`${figtree.className} text-gray-600 block mb-2`}>Title</label>
                                <input
                                    type="text"
                                    value={formData.title}
                                    onChange={(e) => handleChange('title', e.target.value)}
                                    placeholder="e.g. Charming Lakeside Cabin"
                                    className={`${figtree.className} w-full p-4 border-2 border-gray-200 rounded-xl focus:border-black focus:outline-none transition-colors text-lg`}
                                />
                            </div>
                            <div>
                                <label className={`${figtree.className} text-gray-600 block mb-2`}>Description</label>
                                <textarea
                                    value={formData.description}
                                    onChange={(e) => handleChange('description', e.target.value)}
                                    placeholder="Tell guests what makes your place unique..."
                                    rows={5}
                                    className={`${figtree.className} w-full p-4 border-2 border-gray-200 rounded-xl focus:border-black focus:outline-none transition-colors text-lg resize-none`}
                                />
                            </div>
                        </div>
                    </div>
                );
            case 4: // Amenities
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>What does it offer?</h2>
                        <div className="space-y-6">
                            <h3 className={`${figtree.className} text-xl font-semibold`}>Amenities</h3>
                            <div className="grid grid-cols-2 gap-4">
                                {AMENITIES_LIST.map((item) => (
                                    <div
                                        key={item.id}
                                        onClick={() => toggleArrayItem('amenities', item.id)}
                                        className={`cursor-pointer p-4 border-2 rounded-xl flex items-center space-x-3 transition-all ${formData.amenities.includes(item.id) ? 'border-black bg-[#E7FE78]' : 'border-gray-200 hover:border-black'
                                            }`}
                                    >
                                        <item.icon className="w-6 h-6" />
                                        <span className={figtree.className}>{item.label}</span>
                                    </div>
                                ))}
                            </div>
                            <h3 className={`${figtree.className} text-xl font-semibold`}>Safety</h3>
                            <div className="grid grid-cols-2 gap-4">
                                {SAFETY_LIST.map((item) => (
                                    <div
                                        key={item.id}
                                        onClick={() => toggleArrayItem('safety', item.id)}
                                        className={`cursor-pointer p-4 border-2 rounded-xl flex items-center space-x-3 transition-all ${formData.safety.includes(item.id) ? 'border-black bg-[#E7FE78]' : 'border-gray-200 hover:border-black'
                                            }`}
                                    >
                                        <item.icon className="w-6 h-6" />
                                        <span className={figtree.className}>{item.label}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                );
            case 5: // Photos
                return (
                    <div className="space-y-8">
                        <div>
                            <h2 className={`${figtree.className} text-3xl font-bold`}>Add some photos</h2>
                            <p className={`${figtree.className} text-gray-500 mt-2`}>You need at least 5 photos to publish your listing.</p>
                        </div>

                        <div
                            onClick={() => document.getElementById('photo-upload')?.click()}
                            className="border-2 border-dashed border-gray-300 rounded-xl p-12 flex flex-col items-center justify-center space-y-4 hover:border-black transition-colors cursor-pointer bg-gray-50"
                        >
                            <input
                                id="photo-upload"
                                type="file"
                                multiple
                                accept="image/*"
                                className="hidden"
                                onChange={(e) => {
                                    if (e.target.files) {
                                        const newPhotos = Array.from(e.target.files);
                                        setFormData(prev => ({ ...prev, photos: [...prev.photos, ...newPhotos] }));
                                        setError('');
                                    }
                                }}
                            />
                            <UploadSimple className="w-16 h-16 text-gray-400" />
                            <div className="text-center">
                                <p className={`${figtree.className} text-lg font-semibold`}>Click to upload photos</p>
                                <p className={`${figtree.className} text-sm text-gray-500`}>Select multiple files</p>
                            </div>
                        </div>

                        {error && (
                            <div className="p-4 bg-red-50 text-red-600 rounded-lg flex items-center gap-2">
                                <ShieldCheck className="w-5 h-5" />
                                <span className={figtree.className}>{error}</span>
                            </div>
                        )}

                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            {formData.photos.length > 0 && formData.photos.map((photo, index) => (
                                <div key={index} className="aspect-square relative rounded-lg overflow-hidden group">
                                    <Image
                                        src={URL.createObjectURL(photo)}
                                        alt={`Preview ${index}`}
                                        fill
                                        className="object-cover"
                                    />
                                    <button
                                        onClick={() => setFormData(prev => ({
                                            ...prev,
                                            photos: prev.photos.filter((_, i) => i !== index)
                                        }))}
                                        className="absolute top-2 right-2 bg-white p-1 rounded-full shadow-md opacity-0 group-hover:opacity-100 transition-opacity"
                                    >
                                        <X size={16} />
                                    </button>
                                </div>
                            ))}
                        </div>
                    </div>
                );
            case 6: // Instant Approval
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>Finish up</h2>
                        <div className="flex items-center justify-between p-6 border-2 border-gray-200 rounded-xl">
                            <div>
                                <h3 className={`${figtree.className} text-xl font-semibold`}>Instant Approval</h3>
                                <p className={`${figtree.className} text-gray-500 max-w-sm`}>Listings with instant approval get 30% more bookings on average.</p>
                            </div>
                            <button
                                onClick={() => handleChange('instantApproval', !formData.instantApproval)}
                                className={`w-16 h-8 rounded-full transition-colors relative ${formData.instantApproval ? 'bg-[#E7FE78] border-2 border-black' : 'bg-gray-200 border-2 border-transparent'}`}
                            >
                                <div className={`absolute top-1/2 -translate-y-1/2 w-6 h-6 bg-white rounded-full border-2 border-black transition-all ${formData.instantApproval ? 'left-[calc(100%-1.6rem)]' : 'left-1'}`} />
                            </button>
                        </div>
                    </div>
                );
            case 7: // Preview
                return (
                    <div className="space-y-8">
                        <h2 className={`${figtree.className} text-3xl font-bold`}>Review your listing</h2>
                        <div className="border-2 border-black rounded-xl overflow-hidden shadow-[8px_8px_0px_rgba(0,0,0,1)] bg-white">
                            <div className="h-64 bg-gray-200 relative flex items-center justify-center">
                                <Image src="/placeholder-house.jpg" alt="House" width={800} height={400} className="object-cover w-full h-full opacity-50" />
                                <span className={`${figtree.className} absolute text-gray-500`}>Cover Photo</span>
                            </div>
                            <div className="p-6 space-y-4">
                                <div>
                                    <h3 className={`${figtree.className} text-2xl font-bold`}>{formData.title || 'Untitled Listing'}</h3>
                                    <p className={`${figtree.className} text-gray-600 flex items-center gap-2`}>
                                        <MapPin weight="fill" /> {formData.location || 'No location set'}
                                    </p>
                                </div>
                                <div className="flex gap-4 text-sm text-gray-600 border-y py-4">
                                    <span>{formData.guests} Guests</span> •
                                    <span>{formData.bedrooms} Bedrooms</span> •
                                    <span>{formData.beds} Beds</span> •
                                    <span>{formData.bathrooms} Baths</span>
                                </div>
                                <p className={`${figtree.className} text-gray-700`}>{formData.description || 'No description provided.'}</p>
                                <div className="flex flex-wrap gap-2">
                                    {formData.amenities.map(a => (
                                        <span key={a} className="px-3 py-1 bg-gray-100 rounded-full text-sm">{AMENITIES_LIST.find(i => i.id === a)?.label}</span>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>
                );
            default:
                return null;
        }
    };

    return (
        <div ref={containerRef} className="min-h-[calc(81vh)] w-full bg-white text-black p-8 flex flex-col">
            {/* Header / Progress with max-width for better readability */}
            {!isSuccess && (
                <div className="w-full max-w-6xl mx-auto mb-4">
                    <div className="flex items-center justify-between mb-4">
                        <span className={`${figtree.className} font-bold text-gray-400`}>Step {step + 1} of 8</span>
                        <div className="flex gap-1">
                            {Array.from({ length: 8 }).map((_, i) => (
                                <div
                                    key={i}
                                    className={`h-2 rounded-full transition-all duration-300 ${i <= step ? 'w-8 bg-[#E7FE78] border-2 border-black' : 'w-2 bg-gray-200'}`}
                                />
                            ))}
                        </div>
                    </div>
                </div>
            )}

            {/* Content Form */}
            <div className="flex-1 flex items-center justify-center w-full">
                <div ref={formRef} className="w-full max-w-4xl">
                    {renderStep()}
                </div>
            </div>

            {/* Footer Navigation */}
            {!isSuccess && (
                <div className="flex justify-between items-center pt-8 w-full max-w-6xl mx-auto">
                    <button
                        onClick={handleBack}
                        disabled={step === 0}
                        className={`${figtree.className} text-black font-semibold underline disabled:opacity-0 hover:text-gray-600 transition-colors`}
                    >
                        Back
                    </button>

                    {step === 7 ? (
                        <button
                            onClick={handleSubmit}
                            disabled={isSubmitting}
                            className={`${figtree.className} bg-[#E7FE78] text-black px-8 py-3 rounded-lg font-bold border-2 border-black shadow-[4px_4px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-[2px_2px_0px_rgba(0,0,0,1)] transition-all active:shadow-none active:translate-x-[4px] active:translate-y-[4px] disabled:opacity-50 disabled:cursor-not-allowed`}
                        >
                            {isSubmitting ? 'Submitting...' : 'Submit Listing'}
                        </button>
                    ) : (
                        <button
                            onClick={handleNext}
                            className={`${figtree.className} bg-[#E7FE78] text-black px-8 py-3 rounded-lg font-bold border-2 border-black shadow-[4px_4px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-[2px_2px_0px_rgba(0,0,0,1)] transition-all active:shadow-none active:translate-x-[4px] active:translate-y-[4px] flex items-center gap-2`}
                        >
                            Next <CaretRight weight="bold" />
                        </button>
                    )}
                </div>
            )}
        </div>
    );
}
