import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Badge } from '@admin/components/ui/badge';
import { Head, router, useForm } from '@inertiajs/react';
import { ReactNode, useState } from 'react';
import { toast } from 'sonner';
import {
    ShoppingCart,
    TrendingUp,
    GraduationCap,
    Layout,
    Package,
    CheckCircle2,
    Zap,
    Upload,
    Layers,
    AppWindow,
} from 'lucide-react';
import { cn } from '@admin/lib/utils';
import { Input } from '@admin/components/ui/input';
import { Label } from '@admin/components/ui/label';
import { Textarea } from '@admin/components/ui/textarea';

// ─── Types ───────────────────────────────────────────────────────────────────

interface ProfileAssets {
    branding: {
        default_logo: string | null;
        default_icon: string | null;
        default_favicon: string | null;
    };
    login: {
        login_banner: string | null;
        login_logo: string | null;
        login_icon: string | null;
    };
}

interface Profile {
    name: string;
    slug: string;
    description: string;
    icon: string;
    color: string;
    version: string;
    is_active: boolean;
    apps_count: number;
    modules_count: number;
    assets: ProfileAssets;
}

interface Props {
    profiles: Profile[];
}

// ─── Icon map ─────────────────────────────────────────────────────────────────

const ICON_MAP: Record<string, React.ElementType> = {
    ShoppingCart,
    TrendingUp,
    GraduationCap,
    Layout,
    Package,
    Zap,
};

function ProfileIcon({ name, className }: { name: string; className?: string }) {
    const Icon = ICON_MAP[name] ?? Package;
    return <Icon className={className} />;
}

// ─── Export modal ─────────────────────────────────────────────────────────────

function ExportModal({ onClose }: { onClose: () => void }) {
    const { data, setData, post, processing, errors } = useForm({
        slug: '',
        name: '',
        description: '',
    });

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        post(route('admin.settings.product-profile.export'), {
            onSuccess: () => {
                toast.success('Profile exported successfully. Commit the file to version control.');
                onClose();
            },
            onError: () => toast.error('Failed to export profile.'),
        });
    }

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
            <Card className="w-full max-w-md">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Upload className="h-5 w-5" />
                        Export Current State as Profile
                    </CardTitle>
                    <CardDescription>
                        Captures the current app/module configuration and saves it as a
                        version-controlled config file.
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div className="space-y-1">
                            <Label htmlFor="slug">Profile Slug</Label>
                            <Input
                                id="slug"
                                placeholder="e.g. my-custom-product"
                                value={data.slug}
                                onChange={(e) => setData('slug', e.target.value)}
                            />
                            {errors.slug && <p className="text-sm text-destructive">{errors.slug}</p>}
                            <p className="text-xs text-muted-foreground">
                                Lowercase letters, numbers, and hyphens only.
                            </p>
                        </div>

                        <div className="space-y-1">
                            <Label htmlFor="name">Profile Name</Label>
                            <Input
                                id="name"
                                placeholder="e.g. My Custom Product"
                                value={data.name}
                                onChange={(e) => setData('name', e.target.value)}
                            />
                            {errors.name && <p className="text-sm text-destructive">{errors.name}</p>}
                        </div>

                        <div className="space-y-1">
                            <Label htmlFor="description">Description (optional)</Label>
                            <Textarea
                                id="description"
                                rows={2}
                                placeholder="Short description of this product configuration"
                                value={data.description}
                                onChange={(e) => setData('description', e.target.value)}
                            />
                        </div>

                        <div className="flex justify-end gap-2">
                            <Button type="button" variant="outline" onClick={onClose}>
                                Cancel
                            </Button>
                            <Button type="submit" disabled={processing}>
                                {processing ? 'Exporting…' : 'Export Profile'}
                            </Button>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </div>
    );
}

// ─── Profile card ─────────────────────────────────────────────────────────────

function ProfileCard({ profile, onApply }: { profile: Profile; onApply: (slug: string) => void }) {
    const logo    = profile.assets?.branding?.default_logo ?? null;
    const banner  = profile.assets?.login?.login_banner    ?? null;
    const hasAssets = !!(logo || banner);

    return (
        <Card
            className={cn(
                'relative flex flex-col overflow-hidden transition-all duration-200',
                profile.is_active && 'ring-2 ring-offset-1',
            )}
            style={profile.is_active ? { ['--tw-ring-color' as string]: profile.color } : undefined}
        >
            {profile.is_active && (
                <div
                    className="absolute top-2 right-2 z-10 flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold text-white"
                    style={{ backgroundColor: profile.color }}
                >
                    <CheckCircle2 className="h-3 w-3" />
                    Active
                </div>
            )}

            {/* Banner preview — shown when profile has a banner asset */}
            {banner ? (
                <div className="h-24 w-full overflow-hidden bg-muted">
                    <img
                        src={banner}
                        alt={`${profile.name} banner`}
                        className="h-full w-full object-cover"
                    />
                </div>
            ) : (
                <div
                    className="h-24 w-full flex items-center justify-center"
                    style={{ backgroundColor: profile.color + '22' }}
                >
                    <ProfileIcon name={profile.icon} className="h-10 w-10 opacity-30" style={{ color: profile.color }} />
                </div>
            )}

            <CardHeader className="pb-2 pt-3">
                <div className="flex items-center gap-3">
                    {/* Logo or fallback icon */}
                    {logo ? (
                        <img
                            src={logo}
                            alt={`${profile.name} logo`}
                            className="h-9 w-9 shrink-0 rounded-lg object-contain bg-white border border-border p-1"
                        />
                    ) : (
                        <div
                            className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-white"
                            style={{ backgroundColor: profile.color }}
                        >
                            <ProfileIcon name={profile.icon} className="h-4 w-4" />
                        </div>
                    )}
                    <div className="flex-1 min-w-0">
                        <CardTitle className="text-sm font-semibold">{profile.name}</CardTitle>
                        <CardDescription className="mt-0.5 text-xs line-clamp-2">{profile.description}</CardDescription>
                    </div>
                </div>
            </CardHeader>

            <CardContent className="space-y-3 flex-1 flex flex-col justify-end">
                {/* Stats */}
                <div className="flex gap-3">
                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                        <AppWindow className="h-3 w-3" />
                        <span>{profile.apps_count} apps</span>
                    </div>
                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                        <Layers className="h-3 w-3" />
                        <span>{profile.modules_count} modules</span>
                    </div>
                    <Badge variant="outline" className="ml-auto text-xs">
                        v{profile.version}
                    </Badge>
                </div>

                {/* Apply button */}
                <Button
                    className="w-full"
                    size="sm"
                    variant={profile.is_active ? 'outline' : 'default'}
                    disabled={profile.is_active}
                    onClick={() => onApply(profile.slug)}
                    style={!profile.is_active ? { backgroundColor: profile.color, borderColor: profile.color } : undefined}
                >
                    {profile.is_active ? (
                        <>
                            <CheckCircle2 className="mr-1.5 h-3.5 w-3.5" />
                            Currently Active
                        </>
                    ) : (
                        <>
                            <Zap className="mr-1.5 h-3.5 w-3.5" />
                            Apply Profile
                        </>
                    )}
                </Button>
            </CardContent>
        </Card>
    );
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function ProductProfileIndex({ profiles }: Props) {
    const [applying, setApplying] = useState<string | null>(null);
    const [showExport, setShowExport] = useState(false);

    function handleApply(slug: string) {
        if (applying) return;

        const profile = profiles.find((p) => p.slug === slug);
        const hasAssets = !!(profile?.assets?.branding?.default_logo || profile?.assets?.login?.login_banner);
        const confirmed = window.confirm(
            `Apply "${profile?.name}" profile?\n\n` +
            `This will:\n` +
            `• Enable ${profile?.apps_count} apps and ${profile?.modules_count} modules\n` +
            `• Update branding colours, login text, and typography settings\n` +
            (hasAssets
                ? `• Apply product logo, icon, favicon, and banner assets\n`
                : `• No asset overrides defined (current uploads preserved)\n`) +
            `\nContinue?`,
        );
        if (!confirmed) return;

        setApplying(slug);
        router.post(
            route('admin.settings.product-profile.apply', { slug }),
            {},
            {
                onSuccess: () => {
                    toast.success(`Profile applied successfully!`);
                },
                onError: () => {
                    toast.error('Failed to apply profile.');
                },
                onFinish: () => setApplying(null),
            },
        );
    }

    return (
        <>
            <Head title="Product Profiles" />

            <div className="space-y-6 p-6">
                {/* Header */}
                <div className="flex items-start justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">Product Profiles</h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Select a profile to configure apps, modules, branding, and settings
                            for your product in one click. Profiles survive database reseeds.
                        </p>
                    </div>
                    <Button variant="outline" size="sm" onClick={() => setShowExport(true)}>
                        <Upload className="mr-2 h-4 w-4" />
                        Export Current State
                    </Button>
                </div>

                {/* Info banner */}
                <div className="rounded-lg border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800 dark:border-blue-800 dark:bg-blue-950/40 dark:text-blue-300">
                    <strong>After running dev:install:</strong> select the profile that matches your
                    product to instantly restore all app, module, branding, and asset configuration.
                    Profiles with defined assets (logo, icon, favicon, banner) will apply them automatically.
                    Profiles with <code className="rounded bg-blue-100 dark:bg-blue-900 px-1">null</code> asset entries leave current uploads untouched.
                </div>

                {/* Profile grid */}
                {profiles.length === 0 ? (
                    <Card>
                        <CardContent className="py-12 text-center text-muted-foreground">
                            <Package className="mx-auto mb-3 h-10 w-10 opacity-30" />
                            <p>No product profiles found.</p>
                            <p className="text-sm">
                                Add <code>.php</code> files to{' '}
                                <code>AdminApp/config/product-profiles/</code>.
                            </p>
                        </CardContent>
                    </Card>
                ) : (
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                        {profiles.map((profile) => (
                            <ProfileCard
                                key={profile.slug}
                                profile={profile}
                                onApply={handleApply}
                            />
                        ))}
                    </div>
                )}

                {/* Developer note */}
                <Card className="border-dashed">
                    <CardContent className="py-4">
                        <p className="text-xs text-muted-foreground">
                            <strong>Developer tip:</strong> After manually configuring apps/modules
                            through the Product Settings page, click{' '}
                            <strong>Export Current State</strong> to generate a new versioned profile
                            file. Commit it to version control so the configuration is never lost.
                            <br />
                            Or run: <code className="rounded bg-muted px-1 py-0.5">php artisan profile:apply --list</code>
                        </p>
                    </CardContent>
                </Card>
            </div>

            {showExport && <ExportModal onClose={() => setShowExport(false)} />}
        </>
    );
}

ProductProfileIndex.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Workspace Settings', href: '/admin/settings/product' },
            { title: 'Product Profiles', href: '/admin/settings/product-profile' },
        ]}
    >
        {page}
    </AdminLayout>
);
