import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm, Link, router } from '@inertiajs/react';
import { Palette, Save, ArrowLeft, Upload, Globe, Hash, Instagram, Twitter, Linkedin, Facebook, Image as ImageIcon } from 'lucide-react';
import { useState, useRef } from 'react';
import { toast } from 'sonner';
import MediaPicker from '@/Components/MediaPicker';

interface Props {
    settings: {
        app_name: string;
        app_tagline: string;
        app_logo: string | null;
        app_favicon: string | null;
        primary_color: string;
        secondary_color: string;
        social_instagram: string | null;
        social_twitter: string | null;
        social_linkedin: string | null;
        social_facebook: string | null;
    };
}

export default function Branding({ settings }: Props) {
    const { data, setData, patch, processing } = useForm({
        app_name: settings.app_name,
        app_tagline: settings.app_tagline,
        primary_color: settings.primary_color,
        secondary_color: settings.secondary_color,
        social_instagram: settings.social_instagram || '',
        social_twitter: settings.social_twitter || '',
        social_linkedin: settings.social_linkedin || '',
        social_facebook: settings.social_facebook || '',
    });

    const [activeTab, setActiveTab] = useState<'identity' | 'visuals' | 'social'>('identity');
    const [pickerOpen, setPickerOpen] = useState(false);
    const [pickerType, setPickerType] = useState<'app_logo' | 'app_favicon' | null>(null);

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        patch(route('admin.settings.branding.update'), {
            onSuccess: () => toast.success('Branding settings updated'),
        });
    };

    const openPicker = (type: 'app_logo' | 'app_favicon') => {
        setPickerType(type);
        setPickerOpen(true);
    };

    const handleMediaSelect = (media: any) => {
        if (!pickerType) return;
        
        // Save the selection immediately to the database using the same logic as before
        router.post(route('admin.settings.branding.logo'), {
            type: pickerType,
            file_url: media.url // We'll update the controller to accept a direct URL too
        }, {
            onSuccess: () => toast.success(`${pickerType === 'app_logo' ? 'Logo' : 'Favicon'} updated`),
        });
    };

    return (
        <AdminLayout>
            <Head title="Branding Settings" />

            <div className="mb-8">
                <Link 
                    href={route('admin.settings.index')}
                    className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] hover:text-ink transition-colors mb-4"
                >
                    <ArrowLeft className="h-3 w-3" />
                    Back to Settings
                </Link>
                <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                    Branding
                </h1>
                <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                    Customize your platform's identity and visual presence.
                </p>
            </div>

            <div className="max-w-4xl">
                {/* Horizontal Tabs - Scrollable on mobile */}
                <div className="flex items-center gap-1 p-1 bg-[#F0EDE8] rounded-2xl mb-8 w-fit max-w-full overflow-x-auto no-scrollbar">
                    {[
                        { id: 'identity', label: 'Identity', icon: Globe },
                        { id: 'visuals', label: 'Visuals', icon: Palette },
                        { id: 'social', label: 'Social Presence', icon: Hash },
                    ].map((tab) => (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => setActiveTab(tab.id as any)}
                            className={`flex items-center gap-2.5 px-6 py-2.5 rounded-xl text-[14px] font-semibold transition-all whitespace-nowrap ${
                                activeTab === tab.id 
                                    ? 'bg-white text-ink shadow-sm' 
                                    : 'text-[#8C92AC] hover:text-ink'
                            }`}
                        >
                            <tab.icon className="h-4 w-4" />
                            {tab.label}
                        </button>
                    ))}
                </div>

                {/* Form Content */}
                <div className="space-y-6">
                    <form onSubmit={submit} className="space-y-6">
                        {activeTab === 'identity' && (
                            <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden">
                                <div className="p-6 space-y-8">
                                    <div className="grid gap-6">
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                                Company Name
                                            </label>
                                            <input 
                                                type="text"
                                                value={data.app_name}
                                                onChange={e => setData('app_name', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none transition-all"
                                                placeholder="Altivate Solutions"
                                            />
                                        </div>
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                                Tagline
                                            </label>
                                            <input 
                                                type="text"
                                                value={data.app_tagline}
                                                onChange={e => setData('app_tagline', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none transition-all"
                                                placeholder="Accelerating digital growth"
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-8">
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-3">
                                                Primary Logo
                                            </label>
                                            <div className="relative group aspect-video rounded-xl bg-[#FAFAF8] border-2 border-dashed border-[#E8E6DF] flex items-center justify-center overflow-hidden">
                                                {settings.app_logo ? (
                                                    <img src={settings.app_logo} alt="Logo" className="max-h-[60%] w-auto object-contain" />
                                                ) : (
                                                    <div className="text-center">
                                                        <ImageIcon className="h-6 w-6 text-[#C0BDBA] mx-auto mb-2" />
                                                        <span className="text-[11px] text-[#8C92AC]">Select from Library</span>
                                                    </div>
                                                )}
                                                <button 
                                                    type="button"
                                                    onClick={() => openPicker('app_logo')}
                                                    className="absolute inset-0 bg-ink/60 text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2 text-[13px] font-medium"
                                                >
                                                    <ImageIcon className="h-4 w-4" />
                                                    Change Logo
                                                </button>
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-3">
                                                Favicon
                                            </label>
                                            <div className="relative group aspect-square w-24 sm:w-32 rounded-xl bg-[#FAFAF8] border-2 border-dashed border-[#E8E6DF] flex items-center justify-center overflow-hidden">
                                                {settings.app_favicon ? (
                                                    <img src={settings.app_favicon} alt="Favicon" className="h-12 w-12 object-contain" />
                                                ) : (
                                                    <ImageIcon className="h-5 w-5 text-[#C0BDBA]" />
                                                )}
                                                <button 
                                                    type="button"
                                                    onClick={() => openPicker('app_favicon')}
                                                    className="absolute inset-0 bg-ink/60 text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center p-2"
                                                >
                                                    <ImageIcon className="h-4 w-4" />
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {activeTab === 'visuals' && (
                            <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden">
                                <div className="p-6 space-y-8">
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-8">
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-3">
                                                Primary Color (Accent)
                                            </label>
                                            <div className="flex gap-4">
                                                <div 
                                                    className="w-14 h-14 rounded-xl border border-[#E8E6DF] shadow-sm shrink-0"
                                                    style={{ backgroundColor: data.primary_color }}
                                                />
                                                <div className="flex-1">
                                                    <input 
                                                        type="text"
                                                        value={data.primary_color}
                                                        onChange={e => setData('primary_color', e.target.value)}
                                                        className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] font-mono outline-none focus:border-accent"
                                                    />
                                                    <input 
                                                        type="color"
                                                        value={data.primary_color}
                                                        onChange={e => setData('primary_color', e.target.value)}
                                                        className="mt-2 w-full h-2 rounded cursor-pointer"
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-3">
                                                Secondary Color
                                            </label>
                                            <div className="flex gap-4">
                                                <div 
                                                    className="w-14 h-14 rounded-xl border border-[#E8E6DF] shadow-sm shrink-0"
                                                    style={{ backgroundColor: data.secondary_color }}
                                                />
                                                <div className="flex-1">
                                                    <input 
                                                        type="text"
                                                        value={data.secondary_color}
                                                        onChange={e => setData('secondary_color', e.target.value)}
                                                        className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] font-mono outline-none focus:border-accent"
                                                    />
                                                    <input 
                                                        type="color"
                                                        value={data.secondary_color}
                                                        onChange={e => setData('secondary_color', e.target.value)}
                                                        className="mt-2 w-full h-2 rounded cursor-pointer"
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Live Preview Sample */}
                                    <div className="mt-8 p-4 sm:p-6 bg-[#FAFAF8] rounded-2xl border border-[#F0EDE8]">
                                        <span className="text-[10px] font-bold text-[#C0BDBA] uppercase tracking-widest block mb-4">UI Preview</span>
                                        <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
                                            <div className="flex gap-3 w-full sm:w-auto">
                                                <button 
                                                    type="button"
                                                    className="flex-1 sm:flex-none px-6 py-2.5 text-white rounded-xl text-[13px] font-semibold"
                                                    style={{ backgroundColor: data.primary_color }}
                                                >
                                                    Primary
                                                </button>
                                                <button 
                                                    type="button"
                                                    className="flex-1 sm:flex-none px-6 py-2.5 text-white rounded-xl text-[13px] font-semibold"
                                                    style={{ backgroundColor: data.secondary_color }}
                                                >
                                                    Secondary
                                                </button>
                                            </div>
                                            <div className="flex-1 h-2 w-full rounded-full overflow-hidden bg-gray-200">
                                                <div className="h-full w-2/3" style={{ backgroundColor: data.primary_color }} />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {activeTab === 'social' && (
                            <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden">
                                <div className="p-6 space-y-6">
                                    {[
                                        { id: 'social_instagram', label: 'Instagram', icon: Instagram, placeholder: 'https://instagram.com/yourbrand' },
                                        { id: 'social_twitter', label: 'Twitter (X)', icon: Twitter, placeholder: 'https://twitter.com/yourbrand' },
                                        { id: 'social_linkedin', label: 'LinkedIn', icon: Linkedin, placeholder: 'https://linkedin.com/company/yourbrand' },
                                        { id: 'social_facebook', label: 'Facebook', icon: Facebook, placeholder: 'https://facebook.com/yourbrand' },
                                    ].map((field) => (
                                        <div key={field.id}>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                                {field.label}
                                            </label>
                                            <div className="relative">
                                                <div className="absolute left-4 top-1/2 -translate-y-1/2">
                                                    <field.icon className="h-4 w-4 text-[#C0BDBA]" />
                                                </div>
                                                <input 
                                                    type="url"
                                                    value={(data as any)[field.id]}
                                                    onChange={e => setData(field.id as any, e.target.value)}
                                                    className="w-full pl-11 pr-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] outline-none focus:border-accent"
                                                    placeholder={field.placeholder}
                                                />
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="flex justify-end pt-4">
                            <button 
                                type="submit" 
                                disabled={processing}
                                className="w-full sm:w-auto px-10 py-3.5 bg-ink text-white rounded-2xl text-[15px] font-semibold flex items-center justify-center gap-2 hover:bg-accent transition-all shadow-lg shadow-ink/10 active:scale-[0.98] disabled:opacity-50"
                            >
                                <Save className="h-4 w-4" />
                                {processing ? 'Saving...' : 'Save Branding'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <MediaPicker 
                open={pickerOpen}
                onClose={() => setPickerOpen(false)}
                onSelect={handleMediaSelect}
                title={`Select ${pickerType === 'app_logo' ? 'Logo' : 'Favicon'}`}
            />
        </AdminLayout>
    );
}
