import React, { useCallback, useEffect, useRef, useState } from 'react';
import { usePage } from '@inertiajs/react';
import axios from 'axios';
import toast from 'react-hot-toast';

export default function AppNameAndLogo() {
    const { auth } = usePage<{ auth: { user: { api_token: string } } }>().props;
    const token = auth?.user?.api_token;
    const authHeaders = { headers: { Authorization: `Bearer ${token}` } };

    const [appName, setAppName] = useState('');
    const [currentLogo, setCurrentLogo] = useState<string | null>(null);
    const [previewUrl, setPreviewUrl] = useState<string | null>(null);
    const [logoFile, setLogoFile] = useState<File | null>(null);
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [dragOver, setDragOver] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const fetchBranding = useCallback(async () => {
        setLoading(true);
        try {
            const { data } = await axios.get('/api/branding', authHeaders);
            setAppName(data.result.app_name ?? '');
            setCurrentLogo(data.result.app_logo ?? null);
        } catch {
            toast.error('Failed to load branding settings');
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => { fetchBranding(); }, [fetchBranding]);

    const handleFilePick = (file: File) => {
        if (!file.type.startsWith('image/')) {
            toast.error('Please select a valid image file');
            return;
        }
        if (file.size > 2 * 1024 * 1024) {
            toast.error('Image must be smaller than 2 MB');
            return;
        }
        setLogoFile(file);
        setPreviewUrl(URL.createObjectURL(file));
    };

    const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) handleFilePick(file);
    };

    const onDrop = (e: React.DragEvent) => {
        e.preventDefault();
        setDragOver(false);
        const file = e.dataTransfer.files?.[0];
        if (file) handleFilePick(file);
    };

    const clearLogoSelection = () => {
        setLogoFile(null);
        setPreviewUrl(null);
        if (fileInputRef.current) fileInputRef.current.value = '';
    };

    const removeSavedLogo = async () => {
        if (!confirm('Remove the current logo?')) return;
        try {
            await axios.delete('/api/branding/logo', authHeaders);
            setCurrentLogo(null);
            clearLogoSelection();
            toast.success('Logo removed');
        } catch {
            toast.error('Failed to remove logo');
        }
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!appName.trim()) { toast.error('App name is required'); return; }
        setSaving(true);
        try {
            const form = new FormData();
            form.append('app_name', appName.trim());
            if (logoFile) form.append('logo', logoFile);

            const { data } = await axios.post('/api/branding', form, {
                headers: {
                    Authorization: `Bearer ${token}`,
                    'Content-Type': 'multipart/form-data',
                },
            });

            setCurrentLogo(data.result.app_logo ?? null);
            setLogoFile(null);
            setPreviewUrl(null);
            if (fileInputRef.current) fileInputRef.current.value = '';
            toast.success('Branding updated successfully');
        } catch (err: any) {
            const msg = err.response?.data?.errors
                ? Object.values<string[]>(err.response.data.errors).flat().join(' ')
                : err.response?.data?.message ?? 'Failed to save branding';
            toast.error(msg);
        } finally {
            setSaving(false);
        }
    };

    // The logo to display: new preview takes priority, then saved logo
    const displayLogo = previewUrl ?? currentLogo;

    return (
        <div className="bg-white rounded-lg shadow">
            <div className="p-6">
                <div className="mb-5">
                    <h2 className="text-lg font-semibold text-gray-800">App Name &amp; Logo</h2>
                    <p className="text-sm text-gray-500 mt-0.5">
                        Customise how your application appears to users.
                    </p>
                </div>

                {loading ? (
                    <div className="flex justify-center items-center py-16">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
                    </div>
                ) : (
                    <form onSubmit={handleSave} className="max-w-lg space-y-6">

                        {/* App Name */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                App Name <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={appName}
                                onChange={e => setAppName(e.target.value)}
                                placeholder="e.g. Ufanis Law"
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                            />
                            <p className="text-xs text-gray-400 mt-1">
                                Shown in the browser tab, emails, and throughout the application.
                            </p>
                        </div>

                        {/* Logo */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                App Logo
                            </label>

                            {/* Current / preview */}
                            {displayLogo && (
                                <div className="mb-3 flex items-start gap-4 p-3 border border-gray-200 rounded-lg bg-gray-50">
                                    <img
                                        src={displayLogo}
                                        alt="Logo preview"
                                        className="h-16 w-auto object-contain rounded"
                                    />
                                    <div className="flex-1 min-w-0">
                                        <p className="text-sm font-medium text-gray-700">
                                            {previewUrl ? 'New logo (not saved yet)' : 'Current logo'}
                                        </p>
                                        {logoFile && (
                                            <p className="text-xs text-gray-400 truncate mt-0.5">
                                                {logoFile.name} &mdash; {(logoFile.size / 1024).toFixed(1)} KB
                                            </p>
                                        )}
                                        <div className="flex gap-2 mt-2">
                                            {previewUrl && (
                                                <button
                                                    type="button"
                                                    onClick={clearLogoSelection}
                                                    className="text-xs text-gray-500 hover:text-gray-700 underline"
                                                >
                                                    Cancel change
                                                </button>
                                            )}
                                            {currentLogo && !previewUrl && (
                                                <button
                                                    type="button"
                                                    onClick={removeSavedLogo}
                                                    className="text-xs text-red-500 hover:text-red-700 underline"
                                                >
                                                    Remove logo
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Drop zone */}
                            <div
                                onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                                onDragLeave={() => setDragOver(false)}
                                onDrop={onDrop}
                                onClick={() => fileInputRef.current?.click()}
                                className={`h-36 flex flex-col items-center justify-center gap-2 border-2 border-dashed rounded-lg cursor-pointer transition-colors select-none ${
                                    dragOver
                                        ? 'border-indigo-500 bg-indigo-50'
                                        : 'border-gray-300 hover:border-indigo-400 hover:bg-gray-50'
                                }`}
                            >
                                <i className={`fas fa-cloud-upload-alt text-2xl ${dragOver ? 'text-indigo-500' : 'text-gray-400'}`}></i>
                                <p className="text-sm text-gray-500">
                                    <span className="font-medium text-indigo-600">Click to upload</span>
                                    &nbsp;or drag &amp; drop
                                </p>
                                <p className="text-xs text-gray-400">PNG, JPG, SVG, WEBP — max 2 MB</p>
                            </div>
                            <input
                                ref={fileInputRef}
                                type="file"
                                accept="image/png,image/jpeg,image/svg+xml,image/webp"
                                className="hidden"
                                onChange={onFileInputChange}
                            />
                        </div>

                        {/* Save */}
                        <div className="flex items-center gap-3 pt-2">
                            <button
                                type="submit"
                                disabled={saving}
                                className="flex items-center gap-1.5 px-5 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-60 transition-colors text-sm font-medium"
                            >
                                {saving ? (
                                    <>
                                        <span className="animate-spin h-3.5 w-3.5 border-2 border-white border-t-transparent rounded-full inline-block"></span>
                                        Saving…
                                    </>
                                ) : (
                                    <>
                                        <i className="fas fa-save text-xs"></i>
                                        Save Changes
                                    </>
                                )}
                            </button>
                            {(logoFile || appName !== (appName)) && (
                                <span className="text-xs text-amber-600">
                                    <i className="fas fa-circle text-[6px] mr-1 align-middle"></i>
                                    Unsaved changes
                                </span>
                            )}
                        </div>
                    </form>
                )}
            </div>
        </div>
    );
}

