'use client';

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

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);

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

    const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        onPackageChange(e.target.value);
    };

    return (
        <div className="bg-white p-4 rounded-lg shadow mb-6">
            <label htmlFor="package-select" className="block text-sm font-medium text-gray-700 mb-2">
                انتخاب پکیج
            </label>
            <select
                id="package-select"
                value={selectedPackage || ''}
                onChange={handleChange}
                disabled={loading || isLoading}
                className="block w-full px-3 py-2 text-slate-900 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm disabled:opacity-50"
            >
                {loading ? (
                    <option>در حال بارگذاری...</option>
                ) : (
                    packages.map((pkg) => (
                        <option key={pkg.id} value={pkg.name || ''}>
                            {pkg.title} ({pkg.name})
                        </option>
                    ))
                )}
            </select>
        </div>
    );
}