'use client';

import { PackageName } from '@/types/package';
import { useState, useEffect } from 'react';
import { packagesApi } from '@/lib/api/packages';
import { CubeIcon } from '@heroicons/react/24/outline';

interface PackageSelectorProps {
    token: string;
    selectedPackage: string | null;
    onPackageChange: (packageName: string) => void;
    isLoading?: boolean;
}

export default function PackageSelector({ token, selectedPackage, onPackageChange, isLoading }: PackageSelectorProps) {
    const [packages, setPackages] = useState<PackageName[]>([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        loadPackages();
    }, [token]);

    const loadPackages = async () => {
        setLoading(true);
        try {
            const data = await packagesApi.getAllPackages(token);
            setPackages(data);

            if (data.length > 0 && !selectedPackage) {
                onPackageChange(data[0].name!);
            }
        } catch (error) {
            console.error('Failed to load packages:', error);
        } finally {
            setLoading(false);
        }
    };

    if (loading) {
        return (
            <div className="bg-white dark:bg-gray-900 p-4 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm mb-6">
                <div className="animate-pulse flex items-center gap-3">
                    <div className="h-10 w-10 bg-gray-200 dark:bg-gray-800 rounded-xl" />
                    <div className="flex-1">
                        <div className="h-3 w-24 bg-gray-200 dark:bg-gray-800 rounded mb-2" />
                        <div className="h-4 w-48 bg-gray-200 dark:bg-gray-800 rounded" />
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="mb-6">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                پکیج را انتخاب کنید
            </label>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                {packages.map((pkg) => {
                    const isSelected = selectedPackage === pkg.name;
                    return (
                        <button
                            key={pkg.id}
                            onClick={() => onPackageChange(pkg.name!)}
                            disabled={isLoading}
                            className={`flex items-center gap-3 p-4 rounded-2xl text-right transition-all duration-150 ${
                                isSelected
                                    ? 'bg-indigo-50 dark:bg-indigo-500/10 ring-2 ring-indigo-600 dark:ring-indigo-400 shadow-sm'
                                    : 'bg-white dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-800 hover:ring-gray-300 dark:hover:ring-gray-700 hover:shadow-sm'
                            } disabled:opacity-50`}
                        >
                            {pkg.image && typeof pkg.image === 'string' ? (
                                <img src={pkg.image} alt={pkg.title || ''} className="h-10 w-10 rounded-xl object-cover flex-shrink-0" />
                            ) : (
                                <div className={`h-10 w-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
                                    isSelected
                                        ? 'bg-indigo-100 dark:bg-indigo-500/15'
                                        : 'bg-gray-100 dark:bg-gray-800'
                                }`}>
                                    <CubeIcon className={`h-5 w-5 ${isSelected ? 'text-indigo-600 dark:text-indigo-400' : 'text-gray-400 dark:text-gray-500'}`} />
                                </div>
                            )}
                            <div className="min-w-0">
                                <p className={`text-sm font-semibold truncate ${
                                    isSelected ? 'text-indigo-700 dark:text-indigo-400' : 'text-gray-900 dark:text-gray-100'
                                }`}>
                                    {pkg.title || 'بدون عنوان'}
                                </p>
                                <p className="text-xs text-gray-500 dark:text-gray-400 truncate" dir="ltr">
                                    {pkg.name}
                                </p>
                            </div>
                            {isSelected && (
                                <div className="mr-auto flex-shrink-0">
                                    <div className="h-5 w-5 rounded-full bg-indigo-600 dark:bg-indigo-400 flex items-center justify-center">
                                        <svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={3} stroke="currentColor">
                                            <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
                                        </svg>
                                    </div>
                                </div>
                            )}
                        </button>
                    );
                })}
            </div>
        </div>
    );
}
