import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { cn } from '@admin/lib/utils';
import { ColumnDef } from '@tanstack/react-table';
import { Edit, Eye, Globe, Lock, Server } from 'lucide-react';

export interface SaasAppInstance {
    id: number;
    uid: string;
    name: string;
    slug: string;
    url: string;
    host?: string;
    port?: number;
    type: 'public' | 'private';
    status: number;
    status_info: {
        value: number;
        name: string;
    };
    is_default: boolean;
    description?: string;
    created_at: string;
    updated_at: string;
}

const getStatusColor = (statusValue: number): string => {
    switch (statusValue) {
        case 1:
            return 'bg-green-100 text-green-800 border-green-300';
        case 0:
        default:
            return 'bg-gray-100 text-gray-800 border-gray-300';
    }
};

const getTypeIcon = (type: string) => {
    switch (type) {
        case 'public':
            return <Globe className="h-3 w-3 text-blue-600" />;
        case 'private':
            return <Lock className="h-3 w-3 text-amber-600" />;
        default:
            return <Server className="h-3 w-3 text-gray-600" />;
    }
};

const getTypeColor = (type: string): string => {
    switch (type) {
        case 'public':
            return 'bg-blue-100 text-blue-800 border-blue-300';
        case 'private':
            return 'bg-amber-100 text-amber-800 border-amber-300';
        default:
            return 'bg-gray-100 text-gray-800 border-gray-300';
    }
};

interface SaasAppInstanceTableColumnsProps {
    handleViewInstance?: (instance: SaasAppInstance) => void;
    handleEditInstance?: (instance: SaasAppInstance) => void;
}

export const saasAppInstanceTableColumns = ({
    handleViewInstance,
    handleEditInstance,
}: SaasAppInstanceTableColumnsProps = {}): ColumnDef<SaasAppInstance>[] => [
    {
        accessorKey: 'instance',
        header: 'Instance',
        cell: ({ row }) => {
            const instance = row.original;

            return (
                <div className="flex min-w-[220px] flex-col gap-1">
                    {/* Instance Name */}
                    <span className="text-sm font-semibold text-gray-900">
                        {instance.name}
                    </span>

                    {/* URL */}
                    <a
                        href={instance.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-blue-600 hover:underline flex items-center gap-1"
                    >
                        {instance.url}
                    </a>

                    {/* Type and Default badge */}
                    <div className="flex items-center gap-2 mt-1">
                        <span className={cn('rounded-md border px-2 py-0.5 text-xs flex items-center gap-1', getTypeColor(instance.type))}>
                            {getTypeIcon(instance.type)}
                            {instance.type === 'public' ? 'Public' : 'Private'}
                        </span>

                        {instance.is_default && (
                            <Badge variant="secondary" className="text-xs">
                                Default
                            </Badge>
                        )}
                    </div>
                </div>
            );
        },
    },

    // Status
    {
        accessorKey: 'status',
        header: 'Status',
        cell: ({ row }) => {
            const status = row.original.status_info;
            if (!status) return <Badge className="border px-2 py-1 text-sm bg-gray-100 text-gray-800 border-gray-300">Unknown</Badge>;
            const statusColors: Record<string, string> = {
                INACTIVE: 'bg-gray-100 text-gray-800 border-gray-300',
                ACTIVE: 'bg-green-100 text-green-800 border-green-300',
            };
            const color = statusColors[status.name.toUpperCase()] || 'bg-gray-100 text-gray-800 border-gray-300';
            return <Badge className={cn('border px-2 py-1 text-sm', color)}>{status.name}</Badge>;
        },
    },

    // Host & Port
    {
        accessorKey: 'connection',
        header: 'Connection',
        cell: ({ row }) => {
            const { host, port } = row.original;

            if (!host && !port) {
                return <span className="text-xs text-gray-400">Not configured</span>;
            }

            return (
                <div className="flex min-w-[150px] flex-col gap-0.5 text-sm">
                    {host && (
                        <span className="font-mono text-xs text-gray-700 truncate max-w-[150px]" title={host}>
                            {host}
                        </span>
                    )}
                    {port && (
                        <span className="text-xs text-gray-500">
                            Port: {port}
                        </span>
                    )}
                </div>
            );
        },
    },

    // Description
    {
        accessorKey: 'description',
        header: 'Description',
        cell: ({ row }) => {
            const description = row.original.description;
            if (!description) return <span className="text-xs text-gray-400">-</span>;

            return (
                <span className="text-sm text-gray-600 line-clamp-2 max-w-[200px]" title={description}>
                    {description}
                </span>
            );
        },
    },

    // Created At
    {
        accessorKey: 'created_at',
        header: 'Created',
        cell: ({ row }) => {
            const createdAt = row.original.created_at;
            if (!createdAt) return <span className="text-xs text-gray-400">-</span>;

            const date = new Date(createdAt);
            return (
                <span className="text-sm text-gray-600">
                    {date.toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric',
                    })}
                </span>
            );
        },
    },

    {
        id: 'actions',
        header: 'Actions',
        cell: ({ row }) => (
            <div className="flex items-center gap-2">
                {handleViewInstance && (
                    <Button
                        variant="ghost"
                        size="icon"
                        className="size-8 border text-primary"
                        onClick={() => handleViewInstance(row.original)}
                        title="View Details"
                    >
                        <Eye className="size-4 text-success" />
                    </Button>
                )}
                {handleEditInstance && (
                    <Button
                        variant="ghost"
                        size="icon"
                        className="size-8 border text-primary"
                        onClick={() => handleEditInstance(row.original)}
                        title="Edit Instance"
                    >
                        <Edit className="h-5 w-5 text-success" />
                    </Button>
                )}
            </div>
        ),
    },
];
