// src/pages/admin/components/AdminBrandManager.tsx
import React, { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import { fetchAllBrands, uploadBrandLogo } from '../../../services/apiClient';
import { Brand } from '../../../types';
import { ErrorDisplay } from '../../../components/ErrorDisplay';
import { useApiOnMount } from '../../../hooks/useApiOnMount';

export const AdminBrandManager: React.FC = () => {
    // Use the new hook to fetch brands when the component mounts.
    // It handles loading and error states for us. We create a wrapper function
    // to ensure the AbortSignal from the hook is correctly passed to the API client.
    // The underlying `fetchAllBrands` function takes no arguments, so we create a wrapper
    // that accepts the signal from the hook but doesn't pass it down.
    const fetchBrandsWrapper = () => fetchAllBrands();
    const { data: initialBrands, loading, error } = useApiOnMount<Brand[], []>(fetchBrandsWrapper, []);

    // We still need local state for brands so we can update it after a logo upload
    // without needing to re-fetch the entire list.
    const [brands, setBrands] = useState<Brand[]>([]);

    useEffect(() => {
        if (initialBrands) setBrands(initialBrands);
    }, [initialBrands]);

    const handleLogoUpload = async (brandId: number, file: File) => {
        if (!file) {
            toast.error('Please select a file to upload.');
            return;
        }

        // Basic file type and size validation
        if (!['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml'].includes(file.type)) {
            toast.error('Invalid file type. Please upload a PNG, JPG, WEBP, or SVG.');
            return;
        }
        if (file.size > 2 * 1024 * 1024) { // 2MB limit
            toast.error('File is too large. Maximum size is 2MB.');
            return;
        }

        const toastId = toast.loading('Uploading logo...');

        try {
            const response = await uploadBrandLogo(brandId, file);
            const { logoUrl } = await response.json();
            toast.success('Logo updated successfully!', { id: toastId });

            // Update the state to show the new logo immediately
            setBrands(prevBrands =>
                prevBrands.map(brand =>
                    brand.brand_id === brandId ? { ...brand, logo_url: logoUrl } : brand
                )
            );
        } catch (e) {
            const errorMessage = e instanceof Error ? e.message : String(e);
            toast.error(`Upload failed: ${errorMessage}`, { id: toastId });
        }
    };

    if (loading) {
        return <div className="text-center p-4">Loading brands...</div>;
    }

    if (error) {
        return <ErrorDisplay message={`Failed to load brands: ${error.message}`} />;
    }

    return (
        <div className="bg-white dark:bg-gray-800 shadow-md rounded-lg p-6">
            <h2 className="text-2xl font-semibold text-gray-800 dark:text-white mb-4">Brand Management</h2>
            <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead className="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Logo</th>
                            <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Brand Name</th>
                            <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Upload New Logo</th>
                        </tr>
                    </thead>
                    <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                        {brands.map((brand) => (
                            <tr key={brand.brand_id}>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    {brand.logo_url ? (
                                        <img src={brand.logo_url} alt={`${brand.name} logo`} className="h-10 w-10 object-contain rounded-md bg-gray-100 dark:bg-gray-700 p-1" />
                                    ) : (
                                        <div className="h-10 w-10 flex items-center justify-center bg-gray-200 dark:bg-gray-700 rounded-md text-gray-400 text-xs">No Logo</div>
                                    )}
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
                                    {brand.name}
                                    {brand.store_name && <span className="ml-2 text-xs text-gray-500 dark:text-gray-400">({brand.store_name})</span>}
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap text-sm">
                                    <input
                                        // Add an accessible label to make the input findable in tests.
                                        aria-label={`Upload logo for ${brand.name}`}
                                        type="file"
                                        accept="image/png, image/jpeg, image/webp, image/svg+xml"
                                        onChange={(e) => e.target.files && handleLogoUpload(brand.brand_id, e.target.files[0])}
                                        className="text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-brand-light file:text-brand-dark hover:file:bg-brand-primary/20"
                                    />
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
};