"use client";

import { useState, useRef } from "react";
import gsap from "gsap";
import { useGSAP } from "@gsap/react";
import { CaretLeft, CaretRight } from "@phosphor-icons/react/dist/ssr";

import { FormData, FormValue } from "./types";
import { containerStyle, buttonStyle, secondaryButtonStyle, figtree } from "./styles";

import { PropertyType } from "./PropertyType";
import { PropertyPlaceType } from "./PropertyPlaceType";
import { PropertyLocation } from "./PropertyLocation";
import { PropertyCapacity } from "./PropertyCapacity";
import { PropertyAmenities } from "./PropertyAmenities";
import { PropertyDescription } from "./PropertyDescription";
import { PropertyPhotos } from "./PropertyPhotos";
import { PropertyPrice } from "./PropertyPrice";
import { PropertyInstantApproval } from "./PropertyInstantApproval";
import { SafetyDetails } from "./SafetyDetails";
import { LivePreview } from "./LivePreview";

function List() {
    const [step, setStep] = useState(0);
    const [direction, setDirection] = useState(1);
    const [formData, setFormData] = useState<FormData>({
        guests: 1,
        bedrooms: 1,
        beds: 1,
        bathrooms: 1,
    });
    const contentRef = useRef<HTMLDivElement>(null);

    const steps = [
        PropertyType,
        PropertyPlaceType,
        PropertyLocation,
        PropertyCapacity,
        PropertyAmenities,
        PropertyDescription,
        PropertyPhotos,
        PropertyPrice,
        PropertyInstantApproval,
        SafetyDetails
    ];

    const phases = [
        { name: "Basics", start: 0, end: 4 },
        { name: "Description", start: 5, end: 6 },
        { name: "Publish", start: 7, end: 9 }
    ];

    const currentPhaseIndex = phases.findIndex(p => step >= p.start && step <= p.end);
    const currentPhase = phases[currentPhaseIndex];

    const CurrentStepComponent = steps[step];
    const totalSteps = steps.length;

    const updateData = (key: keyof FormData, value: FormValue) => {
        setFormData(prev => ({ ...prev, [key]: value }));
    };

    const handleNext = () => {
        // Validation for photos
        if (step === 6 && (!formData.photos || formData.photos.length < 5)) {
            alert("Please upload at least 5 photos to continue.");
            return;
        }

        if (step < steps.length - 1) {
            setDirection(1);
            setStep(prev => prev + 1);
        }
    };

    const handleBack = () => {
        if (step > 0) {
            setDirection(-1);
            setStep(prev => prev - 1);
        }
    };

    useGSAP(() => {
        if (!contentRef.current) return;
        gsap.fromTo(contentRef.current,
            { x: direction * 20, opacity: 0 },
            { x: 0, opacity: 1, duration: 0.4, ease: "power2.out" }
        );
    }, [step]);

    return (
        <div className="flex min-h-screen w-full bg-white">
            {/* Left Panel - Form */}
            <div className="w-full lg:w-1/2 flex flex-col h-screen relative">
                {/* Header Section */}
                <div className="bg-white z-10 border-b-2 border-gray-100">
                    <div className="px-8 py-6 flex justify-between items-center">
                        <div className="flex items-center gap-4">
                            <div className="w-10 h-10 bg-black text-white rounded-full flex items-center justify-center font-bold text-lg">
                                {step + 1}
                            </div>
                            <div className="flex flex-col">
                                <span className={`${figtree.className} font-bold text-sm uppercase tracking-wider`}>Step {step + 1} of {totalSteps}</span>
                                <span className={`${figtree.className} text-xs text-gray-500`}>{currentPhase.name}</span>
                            </div>
                        </div>
                    </div>

                    {/* Segmented Progress Bar */}
                    <div className="w-full px-8 pb-6 flex gap-2">
                        {phases.map((phase, index) => {
                            let fill = 0;
                            if (index < currentPhaseIndex) {
                                fill = 100;
                            } else if (index === currentPhaseIndex) {
                                const phaseTotal = phase.end - phase.start + 1;
                                const phaseStep = step - phase.start + 1;
                                fill = (phaseStep / phaseTotal) * 100;
                            }

                            return (
                                <div key={phase.name} className="h-1 flex-1 bg-gray-100 rounded-full overflow-hidden relative">
                                    <div
                                        className="absolute top-0 left-0 h-full bg-[#E7FE78] transition-all duration-500 ease-out"
                                        style={{ width: `${fill}%` }}
                                    />
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* Scrollable Content */}
                <div className="flex-1 overflow-y-auto p-8 md:p-12">
                    <div ref={contentRef} className={containerStyle}>
                        <CurrentStepComponent
                            data={formData}
                            updateData={updateData}
                        />
                    </div>
                </div>

                {/* Fixed Footer Navigation */}
                <div className="border-t-2 border-gray-100 p-6 bg-white flex justify-between items-center z-10">
                    <button
                        type="button"
                        onClick={handleBack}
                        disabled={step === 0}
                        className={`${secondaryButtonStyle} ${step === 0 ? 'opacity-0 pointer-events-none' : ''}`}
                    >
                        <CaretLeft size={20} /> Back
                    </button>
                    <button
                        type="button"
                        onClick={handleNext}
                        className={buttonStyle}
                    >
                        {step === totalSteps - 1 ? 'Finish' : 'Next'} <CaretRight size={20} />
                    </button>
                </div>
            </div>

            {/* Right Panel - Live Preview */}
            <div className="hidden lg:flex w-1/2 bg-[#F7F7F7] border-l-2 border-black relative flex-col items-center justify-center p-12 overflow-hidden">
                {/* Background Pattern */}
                <div className="absolute inset-0 opacity-5"
                    style={{
                        backgroundImage: `radial-gradient(circle at 2px 2px, black 1px, transparent 0)`,
                        backgroundSize: '24px 24px'
                    }}
                />

                <div className="relative z-10 w-full max-w-lg">
                    <div className="mb-8 text-center">
                        <h2 className={`${figtree.className} text-3xl font-bold mb-2`}>What guests will see</h2>
                        <p className={`${figtree.className} text-gray-500`}>As you update your listing, see how it looks in search results.</p>
                    </div>
                    <LivePreview data={formData} />
                </div>
            </div>
        </div>
    )
}

export default List;
