'use client'

import React, {useEffect, useState} from 'react'
import {AnimatePresence, motion} from 'framer-motion'
import {useRouter} from 'next/navigation'
import {Button} from "@/components/ui/button"
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
import {Input} from "@/components/ui/input"
import {Switch} from "@/components/ui/switch"
import {Label} from "@/components/ui/label"
import {ScrollArea} from "@/components/ui/scroll-area"
import {Textarea} from "@/components/ui/textarea"
import {Checkbox} from "@/components/ui/checkbox"
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
import {Card, CardContent} from "@/components/ui/card"
import {
    Building,
    Calendar,
    Car,
    Check,
    ChevronLeft,
    ChevronRight,
    File,
    Home,
    MapPin,
    Plus,
    Ruler,
    Upload,
    X,
    Zap
} from 'lucide-react'
import {useToast} from "@/hooks/use-toast";

const propertyTypes = [
    {id: 'apartment', name: 'Appartement', emoji: '🏢'},
    {id: 'house', name: 'Maison', emoji: '🏠'},
    {id: 'studio', name: 'Studio', emoji: '🛋️'},
    {id: 'villa', name: 'Villa', emoji: '🏛️'},
    {id: 'loft', name: 'Loft', emoji: '🏭'},
    {id: 'duplex', name: 'Duplex', emoji: '🏘️'},
    {id: 'commercial', name: 'Local commercial', emoji: '🏪'},
    {id: 'office', name: 'Bureau', emoji: '🏢'},
]

const cities = [
    "Paris", "Marseille", "Lyon", "Toulouse", "Nice", "Nantes", "Strasbourg", "Montpellier", "Bordeaux", "Lille"
]

const roomTypes = [
    {
        id: 'livingroom',
        name: 'Salon',
        emoji: '🛋️',
        forTypes: ['apartment', 'house', 'studio', 'villa', 'loft', 'duplex']
    },
    {
        id: 'bedroom',
        name: 'Chambre',
        emoji: '🛏️',
        forTypes: ['apartment', 'house', 'studio', 'villa', 'loft', 'duplex']
    },
    {id: 'kitchen', name: 'Cuisine', emoji: '🍳', forTypes: ['apartment', 'house', 'studio', 'villa', 'loft', 'duplex']},
    {
        id: 'bathroom',
        name: 'Salle de bain',
        emoji: '🚿',
        forTypes: ['apartment', 'house', 'studio', 'villa', 'loft', 'duplex']
    },
    {id: 'toilet', name: 'Toilettes', emoji: '🚽', forTypes: ['all']},
    {id: 'office', name: 'Bureau', emoji: '💼', forTypes: ['apartment', 'house', 'villa', 'loft', 'duplex', 'office']},
    {id: 'balcony', name: 'Balcon', emoji: '🏞️', forTypes: ['apartment', 'duplex', 'loft']},
    {id: 'garage', name: 'Garage', emoji: '🚗', forTypes: ['house', 'villa']},
    {id: 'garden', name: 'Jardin', emoji: '🌳', forTypes: ['house', 'villa']},
    {id: 'terrace', name: 'Terrasse', emoji: '☀️', forTypes: ['apartment', 'house', 'villa', 'duplex', 'loft']},
    {id: 'basement', name: 'Sous-sol', emoji: '🕳️', forTypes: ['house', 'villa']},
    {id: 'attic', name: 'Grenier', emoji: '🏠', forTypes: ['house', 'villa']},
    {id: 'reception', name: 'Accueil', emoji: '🏢', forTypes: ['commercial', 'office']},
    {id: 'openspace', name: 'Open Space', emoji: '👥', forTypes: ['commercial', 'office']},
    {id: 'meetingroom', name: 'Salle de réunion', emoji: '🤝', forTypes: ['commercial', 'office']},
    {id: 'storage', name: 'Espace de stockage', emoji: '📦', forTypes: ['commercial', 'office']},
]

const inspectionTasks = {
    livingroom: [
        {id: 'walls', name: 'Vérifier les murs'},
        {id: 'floor', name: 'Inspecter le sol'},
        {id: 'windows', name: 'Contrôler les fenêtres'},
        {id: 'lighting', name: 'Vérifier l\'éclairage'},
        {id: 'electrical', name: 'Contrôler les prises électriques'},
    ],
    bedroom: [
        {id: 'closet', name: 'Vérifier les placards'},
        {id: 'lighting', name: 'Contrôler l\'éclairage'},
        {id: 'ventilation', name: 'Vérifier la ventilation'},
        {id: 'windows', name: 'Inspecter les fenêtres'},
        {id: 'flooring', name: 'Examiner le revêtement de sol'},
    ],
    kitchen: [
        {id: 'appliances', name: 'Tester les appareils'},
        {id: 'plumbing', name: 'Vérifier la plomberie'},
        {id: 'countertops', name: 'Inspecter les plans de travail'},
        {id: 'cabinets', name: 'Contrôler les armoires'},
        {id: 'ventilation', name: 'Vérifier la hotte aspirante'},
    ],
    bathroom: [
        {id: 'shower', name: 'Contrôler la douche/baignoire'},
        {id: 'sink', name: 'Vérifier le lavabo'},
        {id: 'toilet', name: 'Inspecter les toilettes'},
        {id: 'tiles', name: 'Examiner le carrelage'},
        {id: 'ventilation', name: 'Vérifier la ventilation'},
    ],
    toilet: [
        {id: 'flush', name: 'Tester la chasse d\'eau'},
        {id: 'seals', name: 'Vérifier les joints'},
        {id: 'plumbing', name: 'Contrôler la plomberie'},
    ],
    office: [
        {id: 'outlets', name: 'Contrôler les prises électriques'},
        {id: 'internet', name: 'Vérifier la connexion internet'},
        {id: 'lighting', name: 'Examiner l\'éclairage'},
    ],
    balcony: [
        {id: 'railing', name: 'Vérifier la rambarde'},
        {id: 'flooring', name: 'Inspecter le revêtement de sol'},
        {id: 'drainage', name: 'Contrôler le drainage'},
    ],
    garage: [
        {id: 'door', name: 'Tester la porte de garage'},
        {id: 'lighting', name: 'Vérifier l\'éclairage'},
        {id: 'storage', name: 'Examiner les espaces de rangement'},
    ],
    garden: [
        {id: 'lawn', name: 'Inspecter la pelouse'},
        {id: 'plants', name: 'Vérifier les plantes et arbres'},
        {id: 'irrigation', name: 'Contrôler le système d\'irrigation'},
    ],
    terrace: [
        {id: 'flooring', name: 'Inspecter le revêtement de sol'},
        {id: 'railing', name: 'Vérifier la rambarde ou le garde-corps'},
        {id: 'drainage', name: 'Contrôler le système de drainage'},
    ],
    basement: [
        {id: 'humidity', name: 'Vérifier le niveau d\'humidité'},
        {id: 'insulation', name: 'Inspecter l\'isolation'},
        {id: 'storage', name: 'Examiner les espaces de rangement'},
    ],
    attic: [
        {id: 'insulation', name: 'Vérifier l\'isolation'},
        {id: 'ventilation', name: 'Contrôler la ventilation'},
        {id: 'roof', name: 'Inspecter la structure du toit'},
    ],
    reception: [
        {id: 'desk', name: 'Vérifier le bureau d\'accueil'},
        {id: 'seating', name: 'Inspecter les sièges pour visiteurs'},
        {id: 'signage', name: 'Contrôler la signalétique'},
    ],
    openspace: [
        {id: 'workstations', name: 'Vérifier les postes de travail'},
        {id: 'networking', name: 'Contrôler les connexions réseau'},
        {id: 'acoustics', name: 'Évaluer l\'acoustique'},
    ],
    meetingroom: [
        {id: 'table', name: 'Inspecter la table de réunion'},
        {id: 'chairs', name: 'Vérifier les chaises'},
        {id: 'av_equipment', name: 'Tester l\'équipement audiovisuel'},
    ],
    storage: [
        {id: 'shelving', name: 'Vérifier les étagères'},
        {id: 'security', name: 'Contrôler la sécurité'},
        {id: 'organization', name: 'Évaluer l\'organisation'},
    ],
}

const sizeBrackets = [
    {value: '10-20', label: '10 - 20 m²'},
    {value: '20-30', label: '20 - 30 m²'},
    {value: '30-50', label: '30 - 50 m²'},
    {value: '50-70', label: '50 - 70 m²'},
    {value: '70-100', label: '70 - 100 m²'},
    {value: '100-150', label: '100 - 150 m²'},
    {value: '150+', label: '150+ m²'},
]

const decades = [
    {value: '2020', label: 'Années 2020', emoji: '🚀'},
    {value: '2010', label: 'Années 2010', emoji: '📱'},
    {value: '2000', label: 'Années 2000', emoji: '💻'},
    {value: '1990', label: 'Années 90', emoji: '🎮'},
    {value: '1980', label: 'Années 80', emoji: '🕹️'},
    {value: '1970', label: 'Années 70', emoji: '🕺'},
    {value: '1960', label: 'Années 60', emoji: '☮️'},
    {value: '1950', label: 'Années 50', emoji: '🎸'},
    {value: '1940', label: 'Avant 1950', emoji: '🏛️'},
]

interface DocumentCategory {
    name: string
    documents: { id: string; name: string }[]
    showFor: string[]
}

const documentCategories: DocumentCategory[] = [
    {
        name: 'Inspection',
        documents: [
            {id: 'last-inspection', name: 'Dernier état des lieux'},
        ],
        showFor: ['all']
    },
    {
        name: 'Administratif',
        documents: [
            {id: 'rental-contract', name: 'Contrat de location'},
            {id: 'property-title', name: 'Titre de propriété'},
            {id: 'insurance', name: 'Attestation d\'assurance'},
        ],
        showFor: ['all']
    },
    {
        name: 'Copropriété',
        documents: [
            {id: 'coop-rules', name: 'Règlements de copropriété'},
        ],
        showFor: ['apartment', 'studio', 'duplex']
    },
    {
        name: 'Commercial',
        documents: [
            {id: 'minutes', name: 'Procès verbaux'},
        ],
        showFor: ['commercial', 'office']
    },
    {
        name: 'Plans',
        documents: [
            {id: 'property-plans', name: 'Plan de propriété'},
        ],
        showFor: ['villa', 'house']
    }
]

const StepIndicator = ({currentStep, totalSteps}: { currentStep: number; totalSteps: number }) => {
    return (
        <div className="flex justify-center items-center space-x-2 mb-6">
            {Array.from({length: totalSteps}, (_, i) => (
                <div
                    key={i}
                    className={`w-8 h-2 rounded-full ${
                        i < currentStep ? 'bg-[#8B5CF6]' : 'bg-gray-300'
                    }`}
                />
            ))}
        </div>
    )
}

export function CreatePropertyComponent() {

    const [step, setStep] = useState(1)
    const [propertyType, setPropertyType] = useState<string>('')
    const [rooms, setRooms] = useState<{ type: string; tasks: string[] }[]>([])
    const [city, setCity] = useState<string>('')
    const [address, setAddress] = useState('')
    const [sizeRange, setSizeRange] = useState<string>('')
    const [decade, setDecade] = useState<string>('')
    const [hasParking, setHasParking] = useState(false)
    const [energyClass, setEnergyClass] = useState<string>('')
    const [additionalDetails, setAdditionalDetails] = useState('')
    const [isSubmitting, setIsSubmitting] = useState(false)
    const [photos, setPhotos] = useState<File[]>([])
    const [documents, setDocuments] = useState<{ [key: string]: File | null }>({})
    const [activeDocTab, setActiveDocTab] = useState('Inspection')

    const {toast} = useToast()
    const router = useRouter()

    useEffect(() => {
        if (propertyType) {
            const defaultRooms = roomTypes
                .filter(room => room.forTypes.includes('all') || room.forTypes.includes(propertyType))
                .map(room => ({
                    type: room.id,
                    tasks: inspectionTasks[room.id as keyof typeof inspectionTasks].map(task => task.id)
                }))
            setRooms(defaultRooms)
        }
    }, [propertyType])

    useEffect(() => {
        // Initialize documents state based on property type
        const relevantDocs = documentCategories
            .filter(cat => cat.showFor.includes('all') || (propertyType && cat.showFor.includes(propertyType)))
            .flatMap(cat => cat.documents)
            .reduce((acc, doc) => ({...acc, [doc.id]: null}), {})
        setDocuments(relevantDocs)
    }, [propertyType])

    const handleAddRoom = (roomType: string) => {
        if (!rooms.some(room => room.type === roomType)) {
            setRooms([...rooms, {
                type: roomType,
                tasks: inspectionTasks[roomType as keyof typeof inspectionTasks].map(task => task.id)
            }])
        }
    }

    const handleRemoveRoom = (roomType: string) => {
        setRooms(rooms.filter(room => room.type !== roomType))
    }

    const handleToggleTask = (roomIndex: number, taskId: string) => {
        const updatedRooms = [...rooms]
        const roomTasks = updatedRooms[roomIndex].tasks
        if (roomTasks.includes(taskId)) {
            updatedRooms[roomIndex].tasks = roomTasks.filter(id => id !== taskId)
        } else {
            updatedRooms[roomIndex].tasks.push(taskId)
        }
        setRooms(updatedRooms)
    }

    const handleNext = () => {
        if (step < 6) {
            setStep(step + 1)
        }
    }

    const handlePrevious = () => {
        if (step > 1) {
            setStep(step - 1)
        }
    }

    const handleSubmit = async () => {
        setIsSubmitting(true)
        try {
            // Simulate API call
            await new Promise(resolve => setTimeout(resolve, 2000))
            // Redirect to success page
            router.push('/properties/create-property-success')
        } catch (error) {
            toast({
                title: "Erreur",
                description: "Une erreur s'est produite lors de la création de la propriété.",
                variant: "destructive",
            })
        } finally {
            setIsSubmitting(false)
        }
    }

    const handlePhotoUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files) {
            const newPhotos = Array.from(event.target.files)
            setPhotos(prev => [...prev, ...newPhotos].slice(0, 10)) // Limit to 10 photos
        }
    }

    const handleRemovePhoto = (index: number) => {
        setPhotos(photos.filter((_, i) => i !== index))
    }

    const handleDocumentUpload = (docId: string, file: File) => {
        setDocuments(prev => ({...prev, [docId]: file}))
    }

    const handleRemoveDocument = (docId: string) => {
        setDocuments(prev => ({...prev, [docId]: null}))
    }

    const renderSummaryCard = () => {
        const selectedPropertyType = propertyTypes.find(type => type.id === propertyType)
        const estimatedTime = rooms.reduce((total, room) => total + room.tasks.length * 10, 0)

        return (
            <div className="space-y-6">
                <h2 className="text-2xl font-bold text-[#8B5CF6]">Résumé</h2>
                <div className="grid md:grid-cols-2 gap-8">
                    <div className="space-y-4">
                        <h3 className="text-xl font-semibold text-[#1F2937]">
                            Type : {selectedPropertyType?.emoji} {selectedPropertyType?.name}
                        </h3>
                        <p className="text-lg text-[#1F2937]"><strong>Ville :</strong> {city}</p>
                        <p className="text-lg text-[#1F2937]"><strong>Adresse :</strong> {address}</p>
                        <p className="text-lg text-[#1F2937]"><strong>Superficie :</strong> {sizeRange}</p>
                        <p className="text-lg text-[#1F2937]"><strong>Décennie
                            :</strong> {decades.find(d => d.value === decade)?.label}</p>
                        <p className="text-lg text-[#1F2937]"><strong>Parking :</strong> {hasParking ? 'Oui' : 'Non'}
                        </p>
                        <p className="text-lg text-[#1F2937]">
                            <strong>Classe énergétique :</strong> {energyClass}
                        </p>
                    </div>
                    <div className="space-y-4">
                        <h3 className="text-xl font-semibold text-[#8B5CF6]">Pièces et tâches</h3>
                        <ScrollArea className="h-[400px] pr-4">
                            {rooms.map((room, index) => (
                                <div key={index} className="mb-4 p-4 bg-gray-50 rounded-lg">
                                    <h4 className="text-lg font-medium mb-2 flex items-center gap-2">
                                        {roomTypes.find(r => r.id === room.type)?.emoji}{' '}
                                        {roomTypes.find(r => r.id === room.type)?.name}
                                    </h4>
                                    <ul className="space-y-2 ml-6 list-disc">
                                        {room.tasks.map(taskId => (
                                            <li key={taskId} className="text-[#1F2937]">
                                                {inspectionTasks[room.type as keyof typeof inspectionTasks]?.find(task => task.id === taskId)?.name}
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            ))}
                        </ScrollArea>
                        <div className="pt-4 border-t">
                            <p className="text-lg font-semibold text-[#1F2937]">
                                Temps d'inspection estimé : {estimatedTime} minutes
                            </p>
                        </div>
                    </div>
                </div>
                {additionalDetails && (
                    <div className="mt-8 pt-6 border-t">
                        <h3 className="text-xl font-semibold mb-3 text-[#8B5CF6]">Détails supplémentaires</h3>
                        <p className="text-[#1F2937]">{additionalDetails}</p>
                    </div>
                )}
                <div className="mt-8 pt-6 border-t">
                    <h3 className="text-xl font-semibold mb-3 text-[#8B5CF6]">Photos</h3>
                    <p className="text-[#1F2937]">{photos.length} photo(s) ajoutée(s)</p>
                </div>
                <div className="mt-8 pt-6 border-t">
                    <h3 className="text-xl font-semibold mb-3 text-[#8B5CF6]">Documents</h3>
                    {Object.entries(documents).map(([docId, file]) => (
                        <p key={docId} className="text-[#1F2937]">
                            <strong>{documentCategories.flatMap(cat => cat.documents).find(doc => doc.id === docId)?.name}:</strong> {file ? 'Ajouté' : 'Non ajouté'}
                        </p>
                    ))}
                </div>
            </div>
        )
    }

    const renderPhotoStep = () => {
        return (
            <div className="space-y-6">
                <h2 className="text-2xl font-bold text-[#8B5CF6]">Photos de la propriété (Optionnel)</h2>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
                    {photos.map((photo, index) => (
                        <div key={index} className="relative aspect-square">
                            <img
                                src={URL.createObjectURL(photo)}
                                alt={`Photo ${index + 1}`}
                                className="w-full h-full object-cover rounded-lg"
                            />
                            <button
                                onClick={() => handleRemovePhoto(index)}
                                className="absolute top-2 right-2 bg-black/50 hover:bg-black/70 text-white rounded-full p-1 transition-colors"
                            >
                                <X className="w-4 h-4"/>
                            </button>
                        </div>
                    ))}
                    {photos.length < 10 && (
                        <label
                            className="aspect-square flex items-center justify-center border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-[#8B5CF6] transition-colors">
                            <div className="flex flex-col items-center">
                                <Plus className="w-8 h-8 text-gray-400"/>
                                <span className="text-sm text-gray-500 mt-2">Ajouter</span>
                            </div>
                            <input
                                type="file"
                                className="hidden"
                                onChange={handlePhotoUpload}
                                multiple
                                accept="image/*"
                            />
                        </label>
                    )}
                </div>
                {photos.length >= 10 && (
                    <p className="text-sm text-amber-600">Limite de 10 photos atteinte</p>
                )}
            </div>
        )
    }

    const renderDocumentStep = () => {
        const relevantCategories = documentCategories.filter(
            cat => cat.showFor.includes('all') || (propertyType && cat.showFor.includes(propertyType))
        )

        return (
            <div className="space-y-6">
                <h2 className="text-2xl font-bold text-[#8B5CF6]">Documents (Optionnel)</h2>
                <Tabs value={activeDocTab} onValueChange={setActiveDocTab}>
                    <TabsList className="grid grid-cols-2 lg:grid-cols-5 mb-6">
                        {relevantCategories.map(category => (
                            <TabsTrigger
                                key={category.name}
                                value={category.name}
                                className="text-sm"
                            >
                                {category.name}
                            </TabsTrigger>
                        ))}
                    </TabsList>
                    {relevantCategories.map(category => (
                        <TabsContent key={category.name} value={category.name}>
                            <Card>
                                <CardContent className="space-y-4 pt-6">
                                    {category.documents.map(doc => (
                                        <div key={doc.id} className="space-y-2">
                                            <Label htmlFor={doc.id}
                                                   className="text-sm font-medium text-[#1F2937] block">
                                                {doc.name}
                                            </Label>
                                            {documents[doc.id] ? (
                                                <div
                                                    className="flex items-center justify-between bg-gray-100 p-3 rounded-lg">
                                                    <div className="flex items-center space-x-2">
                                                        <File className="w-4 h-4 text-[#8B5CF6]"/>
                                                        <span
                                                            className="text-sm text-gray-600">{documents[doc.id]?.name}</span>
                                                    </div>
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() => handleRemoveDocument(doc.id)}
                                                        className="text-red-500 hover:text-red-700 hover:bg-red-100"
                                                    >
                                                        <X className="w-4 h-4"/>
                                                    </Button>
                                                </div>
                                            ) : (
                                                <div className="flex items-center justify-center w-full">
                                                    <label
                                                        htmlFor={doc.id}
                                                        className="flex flex-col items-center justify-center w-full h-32 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100"
                                                    >
                                                        <div
                                                            className="flex flex-col items-center justify-center pt-5 pb-6">
                                                            <Upload className="w-8 h-8 mb-2 text-gray-500"/>
                                                            <p className="text-sm text-gray-500">Cliquez pour
                                                                ajouter</p>
                                                            <p className="text-xs text-gray-500">PDF, DOCX jusqu'à
                                                                10MB</p>
                                                        </div>
                                                        <input
                                                            id={doc.id}
                                                            type="file"
                                                            className="hidden"
                                                            onChange={(e) => e.target.files && handleDocumentUpload(doc.id, e.target.files[0])}
                                                            accept=".pdf,.docx"
                                                        />
                                                    </label>
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </CardContent>
                            </Card>
                        </TabsContent>
                    ))}
                </Tabs>
            </div>
        )
    }

    const renderStep = () => {
        switch (step) {
            case 1:
                return (
                    <AnimatePresence mode="wait">
                        <motion.div
                            key="step1"
                            initial={{opacity: 0, x: 50}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: -50}}
                            transition={{duration: 0.3}}
                        >
                            <div className="space-y-6">
                                <h2 className="text-2xl font-bold text-[#8B5CF6]">Type de propriété</h2>
                                <Select value={propertyType} onValueChange={setPropertyType}>
                                    <SelectTrigger
                                        className="w-full text-lg p-4 bg-[#F5F5F5] border-none rounded-lg h-[65px]">
                                        <Home className="mr-2 h-5 w-5"/>
                                        <SelectValue placeholder="Sélectionnez un type">
                                            {propertyType ? propertyTypes.find(type => type.id === propertyType)?.name : "Sélectionnez un type"}
                                        </SelectValue>
                                    </SelectTrigger>
                                    <SelectContent>
                                        {propertyTypes.map(type => (
                                            <SelectItem key={type.id} value={type.id} className="text-lg p-3">
                                                {type.emoji} {type.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <div className="space-y-4">
                                    <div>
                                        <Label htmlFor="size" className="text-sm font-medium text-[#1F2937] mb-1 block">
                                            Superficie
                                        </Label>
                                        <Select value={sizeRange} onValueChange={setSizeRange}>
                                            <SelectTrigger
                                                className="w-full text-lg p-4 bg-[#F5F5F5] border-none rounded-lg h-[65px]">
                                                <Ruler className="mr-2 h-5 w-5"/>
                                                <SelectValue placeholder="Sélectionnez une plage de superficie">
                                                    {sizeRange ? sizeBrackets.find(bracket => bracket.value === sizeRange)?.label : "Sélectionnez une plage de superficie"}
                                                </SelectValue>
                                            </SelectTrigger>
                                            <SelectContent>
                                                {sizeBrackets.map(bracket => (
                                                    <SelectItem key={bracket.value} value={bracket.value}
                                                                className="text-lg p-3">
                                                        {bracket.label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div>
                                        <Label htmlFor="decade"
                                               className="text-sm font-medium text-[#1F2937] mb-1 block">
                                            Décennie de construction
                                        </Label>
                                        <Select value={decade} onValueChange={setDecade}>
                                            <SelectTrigger
                                                className="w-full text-lg p-4 bg-[#F5F5F5] border-none rounded-lg h-[65px]">
                                                <Calendar className="mr-2 h-5 w-5"/>
                                                <SelectValue placeholder="Sélectionnez une décennie">
                                                    {decade ? `${decades.find(d => d.value === decade)?.emoji} ${decades.find(d => d.value === decade)?.label}` : "Sélectionnez une décennie"}
                                                </SelectValue>
                                            </SelectTrigger>
                                            <SelectContent className="z-50">
                                                {decades.map(d => (
                                                    <SelectItem key={d.value} value={d.value} className="text-lg p-3">
                                                        {d.emoji} {d.label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <Label htmlFor="parking" className="text-sm font-medium text-[#1F2937]">
                                            <Car className="inline-block mr-2 h-5 w-5"/>
                                            Parking disponible
                                        </Label>
                                        <Switch
                                            id="parking"
                                            checked={hasParking}
                                            onCheckedChange={setHasParking}
                                        />
                                    </div>
                                    <div>
                                        <Label htmlFor="energyClass"
                                               className="text-sm font-medium text-[#1F2937] mb-1 block">
                                            Classe énergétique
                                        </Label>
                                        <Select value={energyClass} onValueChange={setEnergyClass}>
                                            <SelectTrigger
                                                className="w-full text-lg p-4 bg-[#F5F5F5] border-none rounded-lg h-[65px]">
                                                <Zap className="mr-2 h-5 w-5"/>
                                                <SelectValue placeholder="Sélectionnez une classe">
                                                    {energyClass || "Sélectionnez une classe"}
                                                </SelectValue>
                                            </SelectTrigger>
                                            <SelectContent>
                                                {['A', 'B', 'C', 'D', 'E', 'F', 'G', 'Je ne sais pas'].map(cls => (
                                                    <SelectItem key={cls} value={cls} className="text-lg p-3">
                                                        {cls}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </div>
                            </div>
                        </motion.div>
                    </AnimatePresence>
                )
            case 2:
                return (
                    <AnimatePresence mode="wait">
                        <motion.div
                            key="step2"
                            initial={{opacity: 0, x: 50}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: -50}}
                            transition={{duration: 0.3}}
                        >
                            <div className="space-y-6">
                                <h2 className="text-2xl font-bold text-[#8B5CF6]">Pièces</h2>
                                <ScrollArea className="h-[300px] border p-4 rounded-lg">
                                    <div className="grid grid-cols-2 gap-4 mb-6">
                                        {roomTypes.filter(room =>
                                            room.forTypes.includes('all') || (propertyType && room.forTypes.includes(propertyType))
                                        ).map(room => (
                                            <Button
                                                key={room.id}
                                                onClick={() => handleAddRoom(room.id)}
                                                variant={rooms.some(r => r.type === room.id) ? "default" : "outline"}
                                                className={`h-[65px] text-lg transition-all rounded-lg ${
                                                    rooms.some(r => r.type === room.id)
                                                        ? 'bg-[#F3E8FF] text-[#8B5CF6] hover:bg-[#EDE9FE] '
                                                        : 'border-gray-300 hover:border-[#8B5CF6] hover:text-[#8B5CF6]'
                                                }`}
                                            >
                                                <div className="flex flex-col items-center">
                                                    <span className="text-2xl mb-1">{room.emoji}</span>
                                                    <span>{room.name}</span>
                                                </div>
                                            </Button>
                                        ))}
                                    </div>
                                </ScrollArea>
                                <div className="space-y-4">
                                    {rooms.map((room, index) => (
                                        <div key={index} className="bg-[#F3F4F6] shadow rounded-lg p-4">
                                            <div className="flex justify-between items-center mb-2">
                                                <h4 className="text-lg font-medium text-[#8B5CF6]">
                                                    {roomTypes.find(r => r.id === room.type)?.emoji} {roomTypes.find(r => r.id === room.type)?.name}
                                                </h4>
                                                <Button
                                                    onClick={() => handleRemoveRoom(room.type)}
                                                    variant="ghost"
                                                    size="sm"
                                                    className="text-red-500 hover:text-red-700 hover:bg-red-100 rounded-lg"
                                                >
                                                    Supprimer
                                                </Button>
                                            </div>
                                            <div className="space-y-2">
                                                {inspectionTasks[room.type as keyof typeof inspectionTasks]?.map(task => (
                                                    <div key={task.id} className="flex items-center">
                                                        <Checkbox
                                                            id={`${room.type}-${task.id}`}
                                                            checked={room.tasks.includes(task.id)}
                                                            onCheckedChange={() => handleToggleTask(index, task.id)}
                                                            className="mr-2 checkbox-purple"
                                                        />
                                                        <Label
                                                            htmlFor={`${room.type}-${task.id}`}
                                                            className="text-sm text-[#1F2937]"
                                                        >
                                                            {task.name}
                                                        </Label>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </motion.div>
                    </AnimatePresence>
                )
            case 3:
                return (
                    <AnimatePresence mode="wait">
                        <motion.div
                            key="step3"
                            initial={{opacity: 0, x: 50}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: -50}}
                            transition={{duration: 0.3}}
                        >
                            <div className="space-y-6">
                                <h2 className="text-2xl font-bold text-[#8B5CF6]">Adresse et détails</h2>
                                <div className="space-y-4">
                                    <div>
                                        <Label htmlFor="city" className="text-sm font-medium text-[#1F2937] mb-1 block">
                                            Ville
                                        </Label>
                                        <Select value={city} onValueChange={setCity}>
                                            <SelectTrigger id="city"
                                                           className="w-full text-lg p-4 bg-[#F5F5F5] border-none rounded-lg h-[65px]">
                                                <Building className="mr-2 h-5 w-5"/>
                                                <SelectValue placeholder="Sélectionnez une ville">
                                                    {city || "Sélectionnez une ville"}
                                                </SelectValue>
                                            </SelectTrigger>
                                            <SelectContent>
                                                {cities.map(city => (
                                                    <SelectItem key={city} value={city} className="text-lg p-3">
                                                        {city}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div>
                                        <Label htmlFor="address"
                                               className="text-sm font-medium text-[#1F2937] mb-1 block">
                                            Adresse
                                        </Label>
                                        <div className="relative">
                                            <MapPin
                                                className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400"/>
                                            <Input
                                                id="address"
                                                placeholder="Adresse de la propriété"
                                                value={address}
                                                onChange={(e) => setAddress(e.target.value)}
                                                className="text-lg pl-12 pr-4 py-4 bg-[#F5F5F5] border-none rounded-lg h-[65px]"
                                            />
                                        </div>
                                    </div>
                                    <div>
                                        <Label htmlFor="details"
                                               className="text-sm font-medium text-[#1F2937] mb-1 block">
                                            Détails supplémentaires
                                        </Label>
                                        <Textarea
                                            id="details"
                                            value={additionalDetails}
                                            onChange={(e) => setAdditionalDetails(e.target.value)}
                                            className="w-full mt-2 p-4 bg-[#F5F5F5] border-none rounded-lg text-lg min-h-[65px]"
                                            rows={4}
                                            placeholder="Ajoutez des détails supplémentaires..."
                                        />
                                    </div>
                                </div>
                            </div>
                        </motion.div>
                    </AnimatePresence>
                )
            case 4:
                return (
                    <AnimatePresence mode="wait">
                        <motion.div
                            key="step4"
                            initial={{opacity: 0, x: 50}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: -50}}
                            transition={{duration: 0.3}}
                        >
                            {renderPhotoStep()}
                        </motion.div>
                    </AnimatePresence>
                )
            case 5:
                return (
                    <AnimatePresence mode="wait">
                        <motion.div
                            key="step5"
                            initial={{opacity: 0, x: 50}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: -50}}
                            transition={{duration: 0.3}}
                        >
                            {renderDocumentStep()}
                        </motion.div>
                    </AnimatePresence>
                )
            case 6:
                return (
                    <AnimatePresence mode="wait">
                        <motion.div
                            key="step6"
                            initial={{opacity: 0, x: 50}}
                            animate={{opacity: 1, x: 0}}
                            exit={{opacity: 0, x: -50}}
                            transition={{duration: 0.3}}
                        >
                            {renderSummaryCard()}
                        </motion.div>
                    </AnimatePresence>
                )
            default:
                return null
        }
    }

    return (
        <div className="p-4 space-y-6 bg-white min-h-screen">
            <header className="flex items-center justify-between mb-6">
                <Button variant="ghost" onClick={handlePrevious} disabled={step === 1}>
                    <ChevronLeft className="h-6 w-6"/>
                </Button>
                <h1 className="text-xl font-bold text-[#1F2937]">Nouvelle propriété</h1>
                <Button variant="ghost" onClick={handleNext} disabled={step === 6}>
                    <ChevronRight className="h-6 w-6"/>
                </Button>
            </header>
            <StepIndicator currentStep={step} totalSteps={6}/>
            {renderStep()}
            <div className="mt-6">
                {step < 6 ? (
                    <Button
                        onClick={handleNext}
                        className="w-full bg-[#8B5CF6] hover:bg-[#7C3AED] text-white text-lg py-4 rounded-lg transition-colors"
                    >
                        {step === 4 || step === 5 ? "Passer" : "Suivant"}
                    </Button>
                ) : (
                    <Button
                        onClick={handleSubmit}
                        className="w-full bg-[#8B5CF6] hover:bg-[#7C3AED] text-white text-lg py-4 rounded-lg transition-colors flex items-center justify-center"
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? (
                            <span className="flex items-center">
                <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg"
                     fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Création en cours...
              </span>
                        ) : (
                            <span className="flex items-center">
                <Check className="mr-2 h-5 w-5"/> Valider
              </span>
                        )}
                    </Button>
                )}
            </div>
        </div>
    )
}