import { Head, useForm } from '@inertiajs/react';
import { Eye, EyeOff, Globe, ImagePlus, Layout, X } from 'lucide-react';
import { FormEventHandler, useRef, useState } from 'react';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AdminLayout from '@/layouts/admin-layout';

interface Setting {
    id: number;
    group_name: string;
    key_name: string;
    value: string | null;
    type: string;
}

type SettingsMap = Record<string, Setting[]>;

function ToggleSwitch({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
    return (
        <button
            type="button"
            onClick={() => onChange(!checked)}
            className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${checked ? 'bg-indigo-600' : 'bg-slate-200'}`}
        >
            <span
                className={`inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ${checked ? 'translate-x-5' : 'translate-x-0'}`}
            />
        </button>
    );
}

export default function AdminSettings({ settings }: { settings: SettingsMap }) {
    const flat = Object.values(settings).flat();
    const { data, setData, post, processing } = useForm<{ settings: Setting[]; logo: File | null }>({
        settings: flat,
        logo: null,
    });

    const [logoPreview, setLogoPreview] = useState<string | null>(
        flat.find((s) => s.group_name === 'header' && s.key_name === 'logo_path')?.value
            ? `/storage/${flat.find((s) => s.group_name === 'header' && s.key_name === 'logo_path')?.value}`
            : null,
    );
    const logoRef = useRef<HTMLInputElement>(null);

    const getSetting = (group: string, key: string) =>
        data.settings.find((s) => s.group_name === group && s.key_name === key);

    const updateSetting = (group: string, key: string, value: string) => {
        setData('settings', data.settings.map((s) =>
            s.group_name === group && s.key_name === key ? { ...s, value } : s,
        ));
    };

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('admin.settings.update'), { forceFormData: true });
    };

    const handleLogo = (file: File | null) => {
        setData('logo', file);
        if (file) {
            setLogoPreview(URL.createObjectURL(file));
        }
    };

    const [activeTab, setActiveTab] = useState<'header' | 'footer' | 'pages' | 'general'>('general');

    const tabs = [
        { id: 'general', label: 'General', icon: <Globe size={15} /> },
        { id: 'header', label: 'Header', icon: <Layout size={15} /> },
        { id: 'footer', label: 'Footer', icon: <Layout size={15} className="rotate-180" /> },
        { id: 'pages', label: 'Pages', icon: <Eye size={15} /> },
    ] as const;

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

            <form onSubmit={submit} className="space-y-4">
                {/* Tabs */}
                <div className="flex gap-1 rounded-xl bg-slate-100 p-1">
                    {tabs.map((tab) => (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => setActiveTab(tab.id)}
                            className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 text-sm font-medium transition-all ${
                                activeTab === tab.id
                                    ? 'bg-white text-indigo-700 shadow-sm'
                                    : 'text-slate-500 hover:text-slate-700'
                            }`}
                        >
                            {tab.icon} {tab.label}
                        </button>
                    ))}
                </div>

                {/* General */}
                {activeTab === 'general' && (
                    <Card>
                        <CardHeader><CardTitle className="text-base">General Settings</CardTitle></CardHeader>
                        <CardContent className="space-y-4">
                            {(['general'] as const).flatMap((group) =>
                                (settings[group] ?? []).map((s) => {
                                    const idx = flat.findIndex((x) => x.id === s.id);
                                    return (
                                        <div key={s.id} className="space-y-1.5">
                                            <Label className="capitalize">{s.key_name.replace(/_/g, ' ')}</Label>
                                            <Input
                                                value={data.settings[idx]?.value ?? ''}
                                                onChange={(e) => {
                                                    const updated = [...data.settings];
                                                    updated[idx] = { ...updated[idx], value: e.target.value };
                                                    setData('settings', updated);
                                                }}
                                            />
                                        </div>
                                    );
                                })
                            )}
                        </CardContent>
                    </Card>
                )}

                {/* Header */}
                {activeTab === 'header' && (
                    <div className="space-y-4">
                        <Card>
                            <CardHeader><CardTitle className="text-base">Logo</CardTitle></CardHeader>
                            <CardContent className="space-y-3">
                                {logoPreview ? (
                                    <div className="relative inline-block">
                                        <img src={logoPreview} alt="Logo" className="h-16 rounded-lg border object-contain bg-slate-50 px-3" />
                                        <button
                                            type="button"
                                            onClick={() => { handleLogo(null); setLogoPreview(null); }}
                                            className="absolute -right-2 -top-2 rounded-full bg-red-500 p-0.5 text-white hover:bg-red-600"
                                        >
                                            <X size={12} />
                                        </button>
                                    </div>
                                ) : (
                                    <div
                                        className="flex cursor-pointer flex-col items-center gap-2 rounded-xl border-2 border-dashed border-slate-300 p-6 text-slate-400 hover:border-indigo-400 hover:bg-indigo-50/30"
                                        onClick={() => logoRef.current?.click()}
                                    >
                                        <ImagePlus size={24} className="text-indigo-400" />
                                        <p className="text-sm">Click to upload logo</p>
                                        <p className="text-xs text-slate-400">PNG, SVG, WEBP recommended</p>
                                    </div>
                                )}
                                <input
                                    ref={logoRef}
                                    type="file"
                                    name="logo"
                                    accept="image/*"
                                    className="hidden"
                                    onChange={(e) => handleLogo(e.target.files?.[0] ?? null)}
                                />
                                {!logoPreview && (
                                    <Button type="button" variant="outline" size="sm" onClick={() => logoRef.current?.click()}>
                                        Choose Logo
                                    </Button>
                                )}
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader><CardTitle className="text-base">Header Content</CardTitle></CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-1.5">
                                    <Label>Site Name</Label>
                                    <Input
                                        value={getSetting('header', 'site_name')?.value ?? ''}
                                        onChange={(e) => updateSetting('header', 'site_name', e.target.value)}
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Tagline</Label>
                                    <Input
                                        value={getSetting('header', 'tagline')?.value ?? ''}
                                        onChange={(e) => updateSetting('header', 'tagline', e.target.value)}
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Phone Number</Label>
                                    <Input
                                        value={getSetting('header', 'phone')?.value ?? ''}
                                        onChange={(e) => updateSetting('header', 'phone', e.target.value)}
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <div className="flex items-center justify-between">
                                        <Label>Announcement Bar</Label>
                                        <ToggleSwitch
                                            checked={getSetting('header', 'show_announcement')?.value === '1'}
                                            onChange={(v) => updateSetting('header', 'show_announcement', v ? '1' : '0')}
                                        />
                                    </div>
                                    <Input
                                        value={getSetting('header', 'announcement_bar')?.value ?? ''}
                                        onChange={(e) => updateSetting('header', 'announcement_bar', e.target.value)}
                                        placeholder="Announcement text shown at top of site"
                                    />
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                )}

                {/* Footer */}
                {activeTab === 'footer' && (
                    <Card>
                        <CardHeader><CardTitle className="text-base">Footer Content</CardTitle></CardHeader>
                        <CardContent className="space-y-4">
                            <div className="space-y-1.5">
                                <Label>Footer Description</Label>
                                <textarea
                                    rows={3}
                                    value={getSetting('footer', 'description')?.value ?? ''}
                                    onChange={(e) => updateSetting('footer', 'description', e.target.value)}
                                    className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                                />
                            </div>
                            <div className="space-y-1.5">
                                <Label>Copyright Text</Label>
                                <Input
                                    value={getSetting('footer', 'copyright')?.value ?? ''}
                                    onChange={(e) => updateSetting('footer', 'copyright', e.target.value)}
                                    placeholder="Use {year} for dynamic year"
                                />
                                <p className="text-xs text-slate-400">Use <code>{'{year}'}</code> to auto-insert current year.</p>
                            </div>
                            <div className="grid gap-4 sm:grid-cols-3">
                                <div className="space-y-1.5">
                                    <Label>Facebook URL</Label>
                                    <Input
                                        value={getSetting('footer', 'facebook')?.value ?? ''}
                                        onChange={(e) => updateSetting('footer', 'facebook', e.target.value)}
                                        placeholder="https://facebook.com/..."
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>Instagram URL</Label>
                                    <Input
                                        value={getSetting('footer', 'instagram')?.value ?? ''}
                                        onChange={(e) => updateSetting('footer', 'instagram', e.target.value)}
                                        placeholder="https://instagram.com/..."
                                    />
                                </div>
                                <div className="space-y-1.5">
                                    <Label>YouTube URL</Label>
                                    <Input
                                        value={getSetting('footer', 'youtube')?.value ?? ''}
                                        onChange={(e) => updateSetting('footer', 'youtube', e.target.value)}
                                        placeholder="https://youtube.com/..."
                                    />
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                )}

                {/* Pages */}
                {activeTab === 'pages' && (
                    <div className="space-y-4">
                        <Card>
                            <CardHeader><CardTitle className="text-base">Page Visibility</CardTitle></CardHeader>
                            <CardContent className="space-y-4">
                                <div className="flex items-center justify-between rounded-xl border border-slate-200 p-4">
                                    <div>
                                        <p className="font-medium text-slate-800">About Us Page</p>
                                        <p className="text-sm text-slate-500">Show or hide the /about page and its nav link</p>
                                    </div>
                                    <ToggleSwitch
                                        checked={getSetting('pages', 'show_about')?.value === '1'}
                                        onChange={(v) => updateSetting('pages', 'show_about', v ? '1' : '0')}
                                    />
                                </div>
                                <div className="flex items-center justify-between rounded-xl border border-slate-200 p-4">
                                    <div>
                                        <p className="font-medium text-slate-800">Blog Page</p>
                                        <p className="text-sm text-slate-500">Show or hide the /blog page and its nav link</p>
                                    </div>
                                    <ToggleSwitch
                                        checked={getSetting('pages', 'show_blog')?.value === '1'}
                                        onChange={(v) => updateSetting('pages', 'show_blog', v ? '1' : '0')}
                                    />
                                </div>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <div className="flex items-center justify-between">
                                    <CardTitle className="text-base">About Us Content</CardTitle>
                                    <a href="/about" target="_blank" className="flex items-center gap-1 text-xs text-indigo-600 hover:underline">
                                        <Eye size={13} /> Preview
                                    </a>
                                </div>
                            </CardHeader>
                            <CardContent>
                                <textarea
                                    rows={8}
                                    value={getSetting('pages', 'about_content')?.value ?? ''}
                                    onChange={(e) => updateSetting('pages', 'about_content', e.target.value)}
                                    className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                                    placeholder="Write your about us content here. Use new lines for paragraphs."
                                />
                            </CardContent>
                        </Card>
                    </div>
                )}

                <Button type="submit" className="bg-indigo-600 hover:bg-indigo-700" disabled={processing}>
                    {processing ? 'Saving…' : 'Save Settings'}
                </Button>
            </form>
        </AdminLayout>
    );
}
