'use client';

import { useEffect, useRef, useState } from 'react';
import { useData } from '../data/DataContext';

export default function Header() {
    const { artist, allArtists, setSelectedArtistId } = useData();
    const [isArtistDropdownOpen, setIsArtistDropdownOpen] = useState(false);
    const artistDropdownRef = useRef<HTMLDivElement>(null);

    // Get first letter of artist name for avatar, fallback to 'A'
    const avatarLetter = artist?.name?.[0]?.toUpperCase() || 'A';

    // Get artist picture from metadata
    const artistMetadata = allArtists.find(a => a.id === artist?.id);
    const artistPicture = artistMetadata?.picture;

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                artistDropdownRef.current &&
                !artistDropdownRef.current.contains(event.target as Node)
            ) {
                setIsArtistDropdownOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () =>
            document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    return (
        <header>
            <div className="flex items-center justify-between max-w-screen-2xl mx-auto px-6 py-6">
                <div className="flex items-center gap-4">
                    {/* Artist Avatar */}
                    <div className="w-16 h-16 rounded-full bg-gradient-to-br from-purple-400 to-pink-300 flex items-center justify-center text-white font-semibold text-xl overflow-hidden">
                        {artistPicture ? (
                            <img
                                src={`/${artistPicture}`}
                                alt={artist?.name || 'Artist'}
                                className="w-full h-full object-cover"
                            />
                        ) : (
                            <span>{avatarLetter}</span>
                        )}
                    </div>

                    {/* Artist Dropdown */}
                    <div className="relative" ref={artistDropdownRef}>
                        <button
                            onClick={() =>
                                setIsArtistDropdownOpen(!isArtistDropdownOpen)
                            }
                            className="flex items-center gap-2 text-2xl font-semibold text-gray-900 hover:text-gray-700 transition-colors"
                        >
                            {artist?.name || 'Loading...'}
                            <svg
                                className={`w-5 h-5 transition-transform ${isArtistDropdownOpen ? 'rotate-180' : ''}`}
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M19 9l-7 7-7-7"
                                />
                            </svg>
                        </button>

                        {isArtistDropdownOpen && (
                            <div className="absolute top-full mt-2 left-0 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-[200px]">
                                {allArtists.map(artistItem => (
                                    <button
                                        key={artistItem.id}
                                        onClick={() => {
                                            setSelectedArtistId(artistItem.id);
                                            setIsArtistDropdownOpen(false);
                                        }}
                                        className={`w-full text-left px-4 py-2.5 hover:bg-gray-50 transition-colors ${
                                            artistItem.id === artist?.id
                                                ? 'bg-purple-50 text-purple-600'
                                                : 'text-gray-700'
                                        }`}
                                    >
                                        {artistItem.name}
                                    </button>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                <div className="flex items-center gap-3 bg-white rounded-lg px-4 py-2.5 border border-gray-200 w-96">
                    <svg
                        className="w-5 h-5 text-gray-400"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                        />
                    </svg>
                    <input
                        type="text"
                        placeholder="Search songs, products and artists"
                        className="flex-1 outline-none text-gray-600 placeholder-gray-400"
                    />
                </div>
            </div>
        </header>
    );
}
