import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import AdminLayout from '@admin/layouts/admin/admin-layout';
import { Head, router } from '@inertiajs/react';
import {
    Activity,
    ArrowLeft,
    CheckCircle2,
    Clock,
    Edit,
    FileText,
    Globe,
    Key,
    Link as LinkIcon,
    Server,
    Settings,
    Shield,
    UserCheck,
    XCircle,
} from 'lucide-react';
import { ReactNode } from 'react';

// Types
interface StatusInfo {
    value: number;
    name: string;
    label: string;
    color: string;
}

interface Settings {
    api_key?: string;
    api_secret?: string;
    webhook_url?: string;
    max_tenants?: number;
    features?: string[];
}

interface SaasAppInstance {
    id: number;
    uid: string;
    name: string;
    slug: string;
    url: string;
    host?: string;
    port?: number;
    type: 'public' | 'private';
    status: number;
    status_info?: StatusInfo;
    is_default: boolean;
    description?: string;
    settings?: Settings;
    metadata?: Record<string, unknown>;
    created_at: string;
    updated_at: string;
    deleted_at?: string;
}

interface SaasAppInstanceShowProps {
    saasAppInstance: SaasAppInstance;
}

// Helper Components
function StatCard({ title, value, icon: Icon, color = 'blue' }: { title: string; value: string | number; icon: any; color?: string }) {
    const colorClasses = {
        blue: 'from-blue-500 to-blue-600',
        green: 'from-green-500 to-green-600',
        purple: 'from-purple-500 to-purple-600',
        orange: 'from-orange-500 to-orange-600',
    };

    return (
        <Card className="border-0 shadow-sm transition-shadow hover:shadow-md">
            <CardContent className="p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <p className="text-xs font-medium text-muted-foreground">{title}</p>
                        <p className="mt-1 text-2xl font-bold">{value}</p>
                    </div>
                    <div className={`rounded-lg bg-gradient-to-br ${colorClasses[color as keyof typeof colorClasses]} p-2.5`}>
                        <Icon className="h-5 w-5 text-white" />
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

function InfoField({ label, value, icon: Icon }: { label: string; value?: string | number | boolean; icon?: any }) {
    if (value === undefined || value === null || value === '') return null;

    return (
        <div className="space-y-1">
            <label className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground uppercase">
                {Icon && <Icon className="h-3 w-3" />}
                {label}
            </label>
            <p className="text-sm font-medium">{typeof value === 'boolean' ? (value ? 'Yes' : 'No') : value}</p>
        </div>
    );
}

function StatusBadge({ status, isDefault }: { status: number; isDefault?: boolean }) {
    const statusConfig: Record<number, { variant: any; label: string }> = {
        1: { variant: 'default', label: 'Active' },
        0: { variant: 'secondary', label: 'Inactive' },
    };

    const config = statusConfig[status] || { variant: 'secondary', label: 'Unknown' };

    return (
        <div className="flex items-center gap-2">
            <Badge variant={config.variant} className="px-2 py-0.5 text-xs">
                {config.label}
            </Badge>
            {isDefault && (
                <Badge variant="outline" className="px-2 py-0.5 text-xs">
                    Default
                </Badge>
            )}
        </div>
    );
}

function SectionTitle({ icon: Icon, title, subtitle }: { icon: any; title: string; subtitle?: string }) {
    return (
        <div className="mb-4 flex items-center gap-2">
            <div className="rounded-md bg-gradient-to-br from-blue-500 to-indigo-600 p-1.5">
                <Icon className="h-4 w-4 text-white" />
            </div>
            <div>
                <h3 className="text-sm font-bold">{title}</h3>
                {subtitle && <p className="text-xs text-muted-foreground">{subtitle}</p>}
            </div>
        </div>
    );
}

// Main Component
export default function SaasAppInstanceShow({ saasAppInstance }: SaasAppInstanceShowProps) {
    const handleEdit = () => {
        router.visit(`/admin/saas-app-instances/${saasAppInstance.id}/edit`);
    };

    const handleBackToList = () => {
        router.visit('/admin/saas-app-instances');
    };

    const typeIcon = saasAppInstance.type === 'public' ? Globe : Shield;

    return (
        <>
            <Head title={`${saasAppInstance.name} - Application Instance Details`} />

            <div className="space-y-4">
                {/* Header Card */}
                <Card className="border-0 shadow-md">
                    <CardContent className="p-4">
                        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                            <div className="flex flex-1 items-start gap-3">
                                <div className="rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 p-3 shadow">
                                    <Server className="h-6 w-6 text-white" />
                                </div>
                                <div className="flex-1">
                                    <div className="mb-1.5 flex flex-wrap items-center gap-2">
                                        <h1 className="text-2xl font-bold text-gray-900">{saasAppInstance.name}</h1>
                                        <StatusBadge status={saasAppInstance.status} isDefault={saasAppInstance.is_default} />
                                        {saasAppInstance.deleted_at && (
                                            <Badge variant="destructive" className="px-2 py-0.5 text-xs">
                                                Deleted
                                            </Badge>
                                        )}
                                    </div>
                                    <div className="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
                                        <span className="flex items-center gap-1.5">
                                            <typeIcon className="h-3.5 w-3.5" />
                                            {saasAppInstance.type === 'public' ? 'Public' : 'Private'}
                                        </span>
                                        <span>•</span>
                                        <span className="flex items-center gap-1.5">
                                            <Globe className="h-3.5 w-3.5" />
                                            <a
                                                href={saasAppInstance.url}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="text-blue-600 hover:underline"
                                            >
                                                {saasAppInstance.url}
                                            </a>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <Button onClick={handleEdit} size="sm" className="bg-blue-600 hover:bg-blue-700">
                                    <Edit className="mr-1.5 h-3.5 w-3.5" />
                                    Edit
                                </Button>
                                <Button variant="outline" size="sm" onClick={handleBackToList}>
                                    <ArrowLeft className="mr-1.5 h-3.5 w-3.5" />
                                    Back
                                </Button>
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {/* Stats Grid */}
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                    <StatCard
                        title="Status"
                        value={saasAppInstance.status === 1 ? 'Active' : 'Inactive'}
                        icon={saasAppInstance.status === 1 ? CheckCircle2 : XCircle}
                        color={saasAppInstance.status === 1 ? 'green' : 'orange'}
                    />
                    <StatCard
                        title="Type"
                        value={saasAppInstance.type === 'public' ? 'Public' : 'Private'}
                        icon={typeIcon}
                        color="blue"
                    />
                    <StatCard
                        title="Max Tenants"
                        value={saasAppInstance.settings?.max_tenants || 'Unlimited'}
                        icon={UserCheck}
                        color="purple"
                    />
                </div>

                {/* Two Column Layout */}
                <div className="mb-5 grid grid-cols-1 gap-4 lg:grid-cols-3">
                    {/* Left Column - Main Info */}
                    <div className="space-y-4 lg:col-span-2">
                        {/* Instance Information */}
                        <Card className="border-0 shadow-sm">
                            <CardContent className="p-4">
                                <SectionTitle icon={Server} title="Instance Information" />
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                    <InfoField label="Name" value={saasAppInstance.name} icon={Server} />
                                    <InfoField label="Slug" value={saasAppInstance.slug} />
                                    <InfoField label="URL" value={saasAppInstance.url} icon={Globe} />
                                    <InfoField label="Type" value={saasAppInstance.type === 'public' ? 'Public' : 'Private'} icon={typeIcon} />
                                    <InfoField label="Host" value={saasAppInstance.host} />
                                    <InfoField label="Port" value={saasAppInstance.port} />
                                </div>

                                {saasAppInstance.description && (
                                    <div className="mt-4 border-t pt-4">
                                        <h4 className="mb-3 flex items-center gap-1.5 text-xs font-semibold text-muted-foreground uppercase">
                                            <FileText className="h-3 w-3" />
                                            Description
                                        </h4>
                                        <p className="text-sm text-muted-foreground">{saasAppInstance.description}</p>
                                    </div>
                                )}
                            </CardContent>
                        </Card>

                        {/* Features */}
                        {saasAppInstance.settings?.features && saasAppInstance.settings.features.length > 0 && (
                            <Card className="border-0 shadow-sm">
                                <CardContent className="p-4">
                                    <SectionTitle
                                        icon={LinkIcon}
                                        title="Features"
                                        subtitle={`${saasAppInstance.settings.features.length} feature${saasAppInstance.settings.features.length > 1 ? 's' : ''} configured`}
                                    />
                                    <div className="flex flex-wrap gap-2">
                                        {saasAppInstance.settings.features.map((feature, idx) => (
                                            <Badge key={idx} variant="secondary" className="px-2 py-1 text-xs">
                                                {feature}
                                            </Badge>
                                        ))}
                                    </div>
                                </CardContent>
                            </Card>
                        )}
                    </div>

                    {/* Right Column - API Configuration & Settings */}
                    <div className="space-y-4">
                        {/* API Configuration */}
                        <Card className="border-0 shadow-sm">
                            <CardContent className="p-4">
                                <SectionTitle icon={Shield} title="API Configuration" />
                                <div className="space-y-3">
                                    <InfoField
                                        label="API Key"
                                        icon={Key}
                                        value={saasAppInstance.settings?.api_key ? '*** Configured ***' : 'Not configured'}
                                    />
                                    <InfoField
                                        label="API Secret"
                                        icon={Key}
                                        value={saasAppInstance.settings?.api_secret ? '*** Configured ***' : 'Not configured'}
                                    />
                                    <InfoField
                                        label="Webhook URL"
                                        icon={Globe}
                                        value={saasAppInstance.settings?.webhook_url}
                                    />
                                </div>
                            </CardContent>
                        </Card>

                        {/* Limits */}
                        <Card className="border-0 shadow-sm">
                            <CardContent className="p-4">
                                <SectionTitle icon={Settings} title="Limits" />
                                <div className="space-y-3">
                                    <InfoField
                                        label="Max Tenants"
                                        value={saasAppInstance.settings?.max_tenants || 'Unlimited'}
                                        icon={UserCheck}
                                    />
                                    <InfoField
                                        label="Features Count"
                                        value={saasAppInstance.settings?.features?.length || 0}
                                        icon={LinkIcon}
                                    />
                                </div>
                            </CardContent>
                        </Card>

                        {/* Metadata */}
                        {saasAppInstance.metadata && Object.keys(saasAppInstance.metadata).length > 0 && (
                            <Card className="border-0 shadow-sm">
                                <CardContent className="p-4">
                                    <SectionTitle icon={FileText} title="Metadata" />
                                    <div className="space-y-2">
                                        {Object.entries(saasAppInstance.metadata).map(([key, value]) => (
                                            <div key={key} className="flex items-start justify-between rounded bg-gray-50/50 p-2">
                                                <span className="text-xs font-medium text-muted-foreground">{key}</span>
                                                <span className="text-xs font-medium">{String(value)}</span>
                                            </div>
                                        ))}
                                    </div>
                                </CardContent>
                            </Card>
                        )}

                        {/* Activity Timeline */}
                        <Card className="border-0 shadow-sm">
                            <CardContent className="p-4">
                                <SectionTitle icon={Activity} title="Activity Timeline" />
                                <div className="space-y-2">
                                    <div className="flex items-start gap-2 rounded border-l-2 border-l-blue-500 bg-blue-50/50 p-2">
                                        <Activity className="mt-0.5 h-3.5 w-3.5 text-blue-600" />
                                        <div className="flex-1">
                                            <p className="text-xs font-medium">Created</p>
                                            <p className="text-xs text-muted-foreground">{new Date(saasAppInstance.created_at).toLocaleString()}</p>
                                        </div>
                                    </div>
                                    <div className="flex items-start gap-2 rounded border-l-2 border-l-green-500 bg-green-50/50 p-2">
                                        <Clock className="mt-0.5 h-3.5 w-3.5 text-green-600" />
                                        <div className="flex-1">
                                            <p className="text-xs font-medium">Updated</p>
                                            <p className="text-xs text-muted-foreground">{new Date(saasAppInstance.updated_at).toLocaleString()}</p>
                                        </div>
                                    </div>
                                    {saasAppInstance.deleted_at && (
                                        <div className="flex items-start gap-2 rounded border-l-2 border-l-red-500 bg-red-50/50 p-2">
                                            <XCircle className="mt-0.5 h-3.5 w-3.5 text-red-600" />
                                            <div className="flex-1">
                                                <p className="text-xs font-medium">Deleted</p>
                                                <p className="text-xs text-muted-foreground">{new Date(saasAppInstance.deleted_at).toLocaleString()}</p>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </>
    );
}

SaasAppInstanceShow.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'App Instances', href: '/admin/saas-app-instances' },
            { title: 'Instance Details', href: '#' },
        ]}
    >
        {page}
    </AdminLayout>
);
