'use client';
import { useState, useRef } from 'react';
import Image from 'next/image';
import localFont from 'next/font/local';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import {
    User,
    Star,
    MapPin,
    Calendar,
    Heart,
    House,
    CheckCircle,
    ShieldCheck,
    Envelope,
    Phone,
    PencilSimple,
    Camera,
    Buildings,
    Bed,
    ChartLine,
    Gear,
    SignOut,
    IdentificationCard,
    CreditCard,
    Bell,
    Lock,
    Globe,
    ChatCircle,
    Medal,
} from '@phosphor-icons/react';

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

interface ProfileData {
    name: string;
    email: string;
    phone: string;
    location: string;
    joinDate: string;
    bio: string;
    avatar: string;
    isVerified: boolean;
    isHost: boolean;
    stats: {
        totalReviews: number;
        rating: number;
        responseRate?: number;
        responseTime?: string;
        properties?: number;
        totalBookings?: number;
        wishlistCount?: number;
    };
}

function Profile() {
    const [activeTab, setActiveTab] = useState<'host' | 'guest'>('guest');
    const [editMode, setEditMode] = useState(false);
    const profileRef = useRef<HTMLDivElement>(null);
    const tabsRef = useRef<HTMLDivElement>(null);

    // Mock profile data - replace with actual data from your backend
    const [profileData, setProfileData] = useState<ProfileData>({
        name: 'Asa Bizanjo',
        email: 'asabizanjo@gmail.com',
        phone: '+92 300 1234567',
        location: 'Karachi, Pakistan',
        joinDate: 'January 2024',
        bio: 'Travel enthusiast and property host. Love meeting new people and sharing the beauty of Pakistan!',
        avatar: '/avatar-placeholder.png',
        isVerified: true,
        isHost: true,
        stats: {
            totalReviews: 47,
            rating: 4.8,
            responseRate: 98,
            responseTime: 'within an hour',
            properties: 3,
            totalBookings: 156,
            wishlistCount: 12,
        },
    });

    useGSAP(() => {
        gsap.fromTo(
            profileRef.current,
            { opacity: 0, y: 30 },
            { opacity: 1, y: 0, duration: 0.8, ease: 'power3.out' }
        );
    });

    const handleTabSwitch = (tab: 'host' | 'guest') => {
        gsap.to(tabsRef.current, {
            opacity: 0,
            y: -10,
            duration: 0.2,
            onComplete: () => {
                setActiveTab(tab);
                gsap.to(tabsRef.current, {
                    opacity: 1,
                    y: 0,
                    duration: 0.3,
                });
            },
        });
    };

    return (
        <div ref={profileRef} className={`${figtree.className} max-w-7xl mx-auto px-4 py-8`}>
            {/* Header Section with Profile Info */}
            <div className="border-4 border-black rounded-xl p-8 mb-8 shadow-[8px_8px_0px_rgba(0,0,0,1)] bg-white hover:shadow-[12px_12px_0px_rgba(0,0,0,1)] transition-all duration-300">
                <div className="flex flex-col md:flex-row gap-8 items-start">
                    {/* Avatar Section */}
                    <div className="relative group">
                        <div className="w-40 h-40 rounded-full border-4 border-black overflow-hidden bg-gray-200 shadow-[4px_4px_0px_rgba(0,0,0,1)]">
                            <div className="w-full h-full flex items-center justify-center bg-[#E7FE78]">
                                <User size={80} weight="bold" />
                            </div>
                        </div>
                        <button className="absolute bottom-0 right-0 bg-[#E7FE78] border-2 border-black rounded-full p-2 shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:scale-110 transition-all duration-300">
                            <Camera size={20} weight="bold" />
                        </button>
                        {profileData.isVerified && (
                            <div className="absolute -top-2 -right-2 bg-blue-500 border-2 border-black rounded-full p-1">
                                <CheckCircle size={24} weight="fill" className="text-white" />
                            </div>
                        )}
                    </div>

                    {/* Profile Info */}
                    <div className="flex-1">
                        <div className="flex items-start justify-between mb-4">
                            <div>
                                <div className="flex items-center gap-3 mb-2">
                                    <h1 className="text-4xl font-bold">{profileData.name}</h1>
                                    {profileData.isHost && (
                                        <span className="bg-[#E7FE78] border-2 border-black px-3 py-1 rounded-lg text-sm font-bold shadow-[2px_2px_0px_rgba(0,0,0,1)]">
                                            SUPERHOST
                                        </span>
                                    )}
                                </div>
                                <div className="flex items-center gap-4 text-gray-600 mb-3">
                                    <div className="flex items-center gap-1">
                                        <MapPin size={18} weight="bold" />
                                        <span>{profileData.location}</span>
                                    </div>
                                    <div className="flex items-center gap-1">
                                        <Calendar size={18} weight="bold" />
                                        <span>Joined {profileData.joinDate}</span>
                                    </div>
                                </div>
                            </div>
                            <button
                                onClick={() => setEditMode(!editMode)}
                                className="bg-white border-2 border-black px-4 py-2 rounded-lg shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:shadow-[4px_4px_0px_rgba(0,0,0,1)] hover:scale-105 transition-all duration-300 font-bold"
                            >
                                <PencilSimple size={20} weight="bold" className="inline mr-2" />
                                Edit Profile
                            </button>
                        </div>

                        {/* Bio */}
                        <p className="text-gray-700 mb-4">{profileData.bio}</p>

                        {/* Contact Info */}
                        <div className="flex flex-wrap gap-4 mb-4">
                            <div className="flex items-center gap-2 bg-gray-50 border-2 border-black px-3 py-2 rounded-lg">
                                <Envelope size={18} weight="bold" />
                                <span className="text-sm">{profileData.email}</span>
                            </div>
                            <div className="flex items-center gap-2 bg-gray-50 border-2 border-black px-3 py-2 rounded-lg">
                                <Phone size={18} weight="bold" />
                                <span className="text-sm">{profileData.phone}</span>
                            </div>
                        </div>

                        {/* Verification Badges */}
                        <div className="flex flex-wrap gap-3">
                            <div className="flex items-center gap-2 bg-green-50 border-2 border-black px-3 py-2 rounded-lg">
                                <ShieldCheck size={18} weight="fill" className="text-green-600" />
                                <span className="text-sm font-bold">Email Verified</span>
                            </div>
                            <div className="flex items-center gap-2 bg-green-50 border-2 border-black px-3 py-2 rounded-lg">
                                <IdentificationCard size={18} weight="fill" className="text-green-600" />
                                <span className="text-sm font-bold">ID Verified</span>
                            </div>
                            <div className="flex items-center gap-2 bg-green-50 border-2 border-black px-3 py-2 rounded-lg">
                                <Phone size={18} weight="fill" className="text-green-600" />
                                <span className="text-sm font-bold">Phone Verified</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Host/Guest Toggle - Fiverr Style */}
            {profileData.isHost && (
                <div className="border-4 border-black rounded-xl p-2 mb-8 shadow-[8px_8px_0px_rgba(0,0,0,1)] bg-white inline-flex gap-2">
                    <button
                        onClick={() => handleTabSwitch('guest')}
                        className={`px-6 py-3 rounded-lg font-bold transition-all duration-300 ${activeTab === 'guest'
                                ? 'bg-[#E7FE78] border-2 border-black shadow-[2px_2px_0px_rgba(0,0,0,1)]'
                                : 'bg-white hover:bg-gray-50'
                            }`}
                    >
                        <User size={20} weight="bold" className="inline mr-2" />
                        Guest Profile
                    </button>
                    <button
                        onClick={() => handleTabSwitch('host')}
                        className={`px-6 py-3 rounded-lg font-bold transition-all duration-300 ${activeTab === 'host'
                                ? 'bg-[#E7FE78] border-2 border-black shadow-[2px_2px_0px_rgba(0,0,0,1)]'
                                : 'bg-white hover:bg-gray-50'
                            }`}
                    >
                        <House size={20} weight="bold" className="inline mr-2" />
                        Host Dashboard
                    </button>
                </div>
            )}

            {/* Content Area */}
            <div ref={tabsRef}>
                {activeTab === 'guest' ? (
                    <GuestProfile profileData={profileData} />
                ) : (
                    <HostDashboard profileData={profileData} />
                )}
            </div>
        </div>
    );
}

// Guest Profile Component
function GuestProfile({ profileData }: { profileData: ProfileData }) {
    return (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Stats Cards */}
            <div className="lg:col-span-3 grid grid-cols-1 md:grid-cols-3 gap-6">
                <StatCard
                    icon={<Star size={32} weight="fill" className="text-yellow-500" />}
                    title="Reviews"
                    value={profileData.stats.totalReviews.toString()}
                    subtitle={`${profileData.stats.rating} average rating`}
                />
                <StatCard
                    icon={<Bed size={32} weight="bold" />}
                    title="Total Bookings"
                    value={profileData.stats.totalBookings?.toString() || '0'}
                    subtitle="Completed stays"
                />
                <StatCard
                    icon={<Heart size={32} weight="fill" className="text-red-500" />}
                    title="Wishlist"
                    value={profileData.stats.wishlistCount?.toString() || '0'}
                    subtitle="Saved properties"
                />
            </div>

            {/* Recent Bookings */}
            <div className="lg:col-span-2">
                <SectionCard title="Recent Bookings" icon={<Calendar size={24} weight="bold" />}>
                    <div className="space-y-4">
                        <BookingItem
                            propertyName="Luxury Villa in Clifton"
                            location="Karachi, Pakistan"
                            dates="Dec 15-20, 2024"
                            status="Upcoming"
                        />
                        <BookingItem
                            propertyName="Cozy Apartment in F-7"
                            location="Islamabad, Pakistan"
                            dates="Nov 10-15, 2024"
                            status="Completed"
                        />
                        <BookingItem
                            propertyName="Beach House in Hawksbay"
                            location="Karachi, Pakistan"
                            dates="Oct 5-8, 2024"
                            status="Completed"
                        />
                    </div>
                </SectionCard>
            </div>

            {/* Quick Actions */}
            <div className="lg:col-span-1">
                <SectionCard title="Quick Actions" icon={<Gear size={24} weight="bold" />}>
                    <div className="space-y-3">
                        <QuickActionButton icon={<CreditCard size={20} />} text="Payment Methods" />
                        <QuickActionButton icon={<Bell size={20} />} text="Notifications" />
                        <QuickActionButton icon={<Lock size={20} />} text="Privacy & Security" />
                        <QuickActionButton icon={<Globe size={20} />} text="Language & Region" />
                        <QuickActionButton icon={<ChatCircle size={20} />} text="Messages" />
                        <QuickActionButton
                            icon={<SignOut size={20} />}
                            text="Sign Out"
                            variant="danger"
                        />
                    </div>
                </SectionCard>
            </div>

            {/* Reviews */}
            <div className="lg:col-span-3">
                <SectionCard title="Reviews from Hosts" icon={<Star size={24} weight="fill" />}>
                    <div className="space-y-4">
                        <ReviewItem
                            reviewerName="Ahmed Khan"
                            propertyName="Luxury Villa in Clifton"
                            rating={5}
                            date="Nov 2024"
                            comment="Excellent guest! Very respectful and left the property in great condition."
                        />
                        <ReviewItem
                            reviewerName="Sara Ali"
                            propertyName="Cozy Apartment in F-7"
                            rating={5}
                            date="Oct 2024"
                            comment="Perfect guest, would definitely host again!"
                        />
                    </div>
                </SectionCard>
            </div>
        </div>
    );
}

// Host Dashboard Component
function HostDashboard({ profileData }: { profileData: ProfileData }) {
    return (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Host Stats */}
            <div className="lg:col-span-3 grid grid-cols-1 md:grid-cols-4 gap-6">
                <StatCard
                    icon={<Buildings size={32} weight="bold" />}
                    title="Properties"
                    value={profileData.stats.properties?.toString() || '0'}
                    subtitle="Active listings"
                />
                <StatCard
                    icon={<Star size={32} weight="fill" className="text-yellow-500" />}
                    title="Rating"
                    value={profileData.stats.rating.toString()}
                    subtitle={`${profileData.stats.totalReviews} reviews`}
                />
                <StatCard
                    icon={<ChatCircle size={32} weight="bold" />}
                    title="Response Rate"
                    value={`${profileData.stats.responseRate}%`}
                    subtitle={profileData.stats.responseTime || 'N/A'}
                />
                <StatCard
                    icon={<ChartLine size={32} weight="bold" className="text-green-600" />}
                    title="Total Bookings"
                    value={profileData.stats.totalBookings?.toString() || '0'}
                    subtitle="All time"
                />
            </div>

            {/* My Properties */}
            <div className="lg:col-span-2">
                <SectionCard title="My Properties" icon={<House size={24} weight="bold" />}>
                    <div className="space-y-4">
                        <PropertyItem
                            name="Luxury Villa in Clifton"
                            location="Karachi, Pakistan"
                            rating={4.9}
                            reviews={23}
                            bookings={45}
                            status="Active"
                        />
                        <PropertyItem
                            name="Modern Apartment in DHA"
                            location="Karachi, Pakistan"
                            rating={4.7}
                            reviews={18}
                            bookings={32}
                            status="Active"
                        />
                        <PropertyItem
                            name="Beach House in Hawksbay"
                            location="Karachi, Pakistan"
                            rating={4.8}
                            reviews={15}
                            bookings={28}
                            status="Inactive"
                        />
                    </div>
                    <button className="w-full mt-4 bg-[#E7FE78] border-2 border-black px-4 py-3 rounded-lg shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:shadow-[4px_4px_0px_rgba(0,0,0,1)] hover:scale-105 transition-all duration-300 font-bold">
                        + Add New Property
                    </button>
                </SectionCard>
            </div>

            {/* Host Tools */}
            <div className="lg:col-span-1">
                <SectionCard title="Host Tools" icon={<Gear size={24} weight="bold" />}>
                    <div className="space-y-3">
                        <QuickActionButton icon={<Calendar size={20} />} text="Calendar" />
                        <QuickActionButton icon={<ChartLine size={20} />} text="Analytics" />
                        <QuickActionButton icon={<CreditCard size={20} />} text="Earnings" />
                        <QuickActionButton icon={<ChatCircle size={20} />} text="Messages" />
                        <QuickActionButton icon={<Bell size={20} />} text="Notifications" />
                        <QuickActionButton icon={<Gear size={20} />} text="Settings" />
                    </div>
                </SectionCard>

                {/* Achievement Badge */}
                <div className="mt-6 border-4 border-black rounded-xl p-6 bg-gradient-to-br from-yellow-100 to-yellow-200 shadow-[8px_8px_0px_rgba(0,0,0,1)] text-center">
                    <Medal size={48} weight="fill" className="mx-auto mb-3 text-yellow-600" />
                    <h3 className="font-bold text-xl mb-2">Superhost</h3>
                    <p className="text-sm text-gray-700">
                        You&apos;re in the top 10% of hosts in Karachi!
                    </p>
                </div>
            </div>

            {/* Recent Reviews */}
            <div className="lg:col-span-3">
                <SectionCard title="Recent Guest Reviews" icon={<Star size={24} weight="fill" />}>
                    <div className="space-y-4">
                        <ReviewItem
                            reviewerName="John Doe"
                            propertyName="Luxury Villa in Clifton"
                            rating={5}
                            date="Dec 2024"
                            comment="Amazing property! The host was very responsive and helpful. Highly recommend!"
                        />
                        <ReviewItem
                            reviewerName="Jane Smith"
                            propertyName="Modern Apartment in DHA"
                            rating={4}
                            date="Nov 2024"
                            comment="Great location and clean apartment. Had a wonderful stay!"
                        />
                    </div>
                </SectionCard>
            </div>
        </div>
    );
}

// Reusable Components
function StatCard({
    icon,
    title,
    value,
    subtitle,
}: {
    icon: React.ReactNode;
    title: string;
    value: string;
    subtitle: string;
}) {
    return (
        <div className="border-4 border-black rounded-xl p-6 bg-white shadow-[4px_4px_0px_rgba(0,0,0,1)] hover:shadow-[8px_8px_0px_rgba(0,0,0,1)] hover:scale-105 transition-all duration-300">
            <div className="flex items-center gap-4 mb-3">
                {icon}
                <h3 className="font-bold text-lg">{title}</h3>
            </div>
            <p className="text-3xl font-bold mb-1">{value}</p>
            <p className="text-sm text-gray-600">{subtitle}</p>
        </div>
    );
}

function SectionCard({
    title,
    icon,
    children,
}: {
    title: string;
    icon: React.ReactNode;
    children: React.ReactNode;
}) {
    return (
        <div className="border-4 border-black rounded-xl p-6 bg-white shadow-[4px_4px_0px_rgba(0,0,0,1)]">
            <div className="flex items-center gap-3 mb-6 pb-4 border-b-2 border-black">
                {icon}
                <h2 className="text-2xl font-bold">{title}</h2>
            </div>
            {children}
        </div>
    );
}

function QuickActionButton({
    icon,
    text,
    variant = 'default',
}: {
    icon: React.ReactNode;
    text: string;
    variant?: 'default' | 'danger';
}) {
    const bgColor = variant === 'danger' ? 'bg-red-50 hover:bg-red-100' : 'bg-gray-50 hover:bg-gray-100';
    const textColor = variant === 'danger' ? 'text-red-600' : 'text-black';

    return (
        <button
            className={`w-full flex items-center gap-3 ${bgColor} border-2 border-black px-4 py-3 rounded-lg shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:shadow-[4px_4px_0px_rgba(0,0,0,1)] hover:scale-105 transition-all duration-300 font-bold ${textColor}`}
        >
            {icon}
            <span>{text}</span>
        </button>
    );
}

function BookingItem({
    propertyName,
    location,
    dates,
    status,
}: {
    propertyName: string;
    location: string;
    dates: string;
    status: string;
}) {
    const statusColor = status === 'Upcoming' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700';

    return (
        <div className="border-2 border-black rounded-lg p-4 bg-gray-50 hover:bg-gray-100 transition-all duration-300">
            <div className="flex justify-between items-start mb-2">
                <h4 className="font-bold text-lg">{propertyName}</h4>
                <span className={`px-3 py-1 rounded-lg text-xs font-bold border-2 border-black ${statusColor}`}>
                    {status}
                </span>
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-600 mb-1">
                <MapPin size={16} weight="bold" />
                <span>{location}</span>
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-600">
                <Calendar size={16} weight="bold" />
                <span>{dates}</span>
            </div>
        </div>
    );
}

function PropertyItem({
    name,
    location,
    rating,
    reviews,
    bookings,
    status,
}: {
    name: string;
    location: string;
    rating: number;
    reviews: number;
    bookings: number;
    status: string;
}) {
    const statusColor = status === 'Active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700';

    return (
        <div className="border-2 border-black rounded-lg p-4 bg-gray-50 hover:bg-gray-100 transition-all duration-300">
            <div className="flex justify-between items-start mb-2">
                <h4 className="font-bold text-lg">{name}</h4>
                <span className={`px-3 py-1 rounded-lg text-xs font-bold border-2 border-black ${statusColor}`}>
                    {status}
                </span>
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-600 mb-3">
                <MapPin size={16} weight="bold" />
                <span>{location}</span>
            </div>
            <div className="flex gap-4 text-sm">
                <div className="flex items-center gap-1">
                    <Star size={16} weight="fill" className="text-yellow-500" />
                    <span className="font-bold">{rating}</span>
                    <span className="text-gray-600">({reviews})</span>
                </div>
                <div className="flex items-center gap-1">
                    <Bed size={16} weight="bold" />
                    <span className="font-bold">{bookings}</span>
                    <span className="text-gray-600">bookings</span>
                </div>
            </div>
        </div>
    );
}

function ReviewItem({
    reviewerName,
    propertyName,
    rating,
    date,
    comment,
}: {
    reviewerName: string;
    propertyName: string;
    rating: number;
    date: string;
    comment: string;
}) {
    return (
        <div className="border-2 border-black rounded-lg p-4 bg-gray-50">
            <div className="flex justify-between items-start mb-3">
                <div>
                    <h4 className="font-bold text-lg">{reviewerName}</h4>
                    <p className="text-sm text-gray-600">{propertyName}</p>
                </div>
                <div className="text-right">
                    <div className="flex items-center gap-1 mb-1">
                        {[...Array(5)].map((_, i) => (
                            <Star
                                key={i}
                                size={16}
                                weight="fill"
                                className={i < rating ? 'text-yellow-500' : 'text-gray-300'}
                            />
                        ))}
                    </div>
                    <p className="text-xs text-gray-600">{date}</p>
                </div>
            </div>
            <p className="text-gray-700">{comment}</p>
        </div>
    );
}

export default Profile;