"use client"

import { useState, useEffect } from "react"
import AppLayout from "@/Layouts/AppLayout"
import { Button } from "@/Components/UI/Button"
import { Badge } from "@/Components/UI/Badge"
import { Input } from "@/Components/UI/Input"
import { Label } from "@/Components/UI/Label"
import { Modal } from "@/Components/UI/Modal"
import { Card, CardContent } from "@/Components/UI/Card"
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/UI/DropdownMenu"
import PlatformIcon from "@/Components/UI/PlatformIcon"
import DeleteModal from "@/Components/DeleteModal"
import { route } from "ziggy-js"
import { router } from "@inertiajs/react"
import useTranslate from "@/hooks/useTranslate"
import { useDeleteHandler } from "@/hooks/useDeleteHandler"

import {
    Plus,
    Eye,
    Link,
    Settings,
    Trash2,
    Users,
    MoreVertical,
    Search,
    ArrowLeft,
    Zap,
    CheckCircle,
    AlertCircle,
    Clock,
    AlertTriangle,
    BarChart3
} from "lucide-react"

export default function PlatformAccounts({ platform, accounts }) {
    const t = useTranslate();
    const [accountList, setAccountList] = useState(accounts.data || [])
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
    const [accountToDelete, setAccountToDelete] = useState(null)
    const [searchQuery, setSearchQuery] = useState("")
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [isSubmitting, setIsSubmitting] = useState(false)
    const [profileToShow, setProfileToShow] = useState(null)
    const [isShowProfileModalOpen, setIsShowProfileModalOpen] = useState(false)
    const [configError, setConfigError] = useState(null)
    const [isConfigErrorModalOpen, setIsConfigErrorModalOpen] = useState(false)

    const [formData, setFormData] = useState({
        label: "",
    });

    const breadcrumbs = [
        { label: "Home", href: route("user.home") },
        { label: "Platforms", href: route("user.platform.index") },
        { label: `${platform.name} Accounts` },
    ]

    useEffect(() => {
        setAccountList(accounts.data || [])

        // Check if user came from connect account modal
        const pendingAccountName = sessionStorage.getItem('pending_account_name');
        const shouldConnect = sessionStorage.getItem('connect_after_redirect');

        if (pendingAccountName && shouldConnect) {
            setFormData({ label: pendingAccountName });
            setIsModalOpen(true);
            sessionStorage.removeItem('pending_account_name');
            sessionStorage.removeItem('connect_after_redirect');
        }
    }, [accounts])

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({
            ...prev,
            [name]: value,
        }));
    };

    const filteredAccounts = accountList.filter(account =>
        account.label?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        account.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        account.username?.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const connectedAccounts = filteredAccounts.filter(account => account.is_connected === "1");
    const disconnectedAccounts = filteredAccounts.filter(account => account.is_connected === "0");

    const isValidPlatformConfig = (platform) => {
        // TikTok uses client_key instead of client_id
        const hasClientId = platform?.configuration?.client_id || platform?.configuration?.client_key;
        const hasClientSecret = platform?.configuration?.client_secret;
        return platform?.configuration && hasClientId && hasClientSecret;
    };

    const handleConnect = (account = null) => {
        // Check if platform is configured
        if (!isValidPlatformConfig(platform)) {
            setConfigError({
                platform: platform,
                message: `${platform.name} API is not configured. Please configure the platform settings first.`
            });
            setIsConfigErrorModalOpen(true);
            return;
        }

        // Use window.location.href for OAuth redirects (external URLs)
        if (account && account.is_connected === "0") {
            // Redirect to connect specific account
            window.location.href = route("user.account.connect", {
                medium: platform.slug,
                account_id: account.id
            });
        } else {
            // General connect
            window.location.href = route("user.account.connect", { medium: platform.slug });
        }
    };

    const handleCreateAccountLabel = () => {
        // Check if platform is configured before creating account
        if (!isValidPlatformConfig(platform)) {
            setConfigError({
                platform: platform,
                message: `${platform.name} API is not configured. Please configure the platform settings first.`
            });
            setIsConfigErrorModalOpen(true);
            setIsModalOpen(false);
            return;
        }

        setIsSubmitting(true)
        router.post(route("user.platform.account.create"), {
            ...formData,
            platform_id: platform.id,
            platform_slug: platform.slug
        }, {
            preserveScroll: true,
            onSuccess: (page) => {
                setIsSubmitting(false)
                setIsModalOpen(false)
                setFormData({ label: "" })

                // Get the newly created account ID from flash data
                const newAccountId = page?.props?.flash?.account?.id;

                // Redirect to OAuth connection with the new account ID
                if (newAccountId) {
                    window.location.href = route("user.account.connect", {
                        medium: platform.slug,
                        account_id: newAccountId
                    });
                } else {
                    // Fallback: redirect without account_id
                    window.location.href = route("user.account.connect", { medium: platform.slug });
                }
            },
            onError: (errors) => {
                setIsSubmitting(false)
                console.error('Account creation failed:', errors)
            }
        })
    }

    const handleViewProfile = (account) => {
        setProfileToShow(account)
        setIsShowProfileModalOpen(true)
    }

    const handleDeleteClick = (account) => {
        setAccountToDelete(account)
        setIsDeleteModalOpen(true)
    }

    const handleDeleteConfirm = () => {
        if (accountToDelete) {
            router.post(route("user.platform.account.delete"), {
                id: accountToDelete.id
            }, {
                onSuccess: () => {
                    setIsDeleteModalOpen(false)
                    setAccountToDelete(null)
                    // Refresh the page to show updated account list
                    router.reload({ only: ['accounts'] })
                },
                onError: (errors) => {
                    console.error('Delete failed:', errors)
                }
            })
        }
    }

    const handleConfigurePlatform = () => {
        const settingsUrl = route("user.platform.setting", platform.id);
        router.visit(settingsUrl, {
            method: "get",
            replace: true,
            preserveState: false,
        });
    };

    const getStatusColor = (account) => {
        if (account.is_connected === "1") {
            return "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800";
        }
        return "bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-400 dark:border-amber-800";
    }

    const getStatusIcon = (account) => {
        if (account.is_connected === "1") {
            return <CheckCircle className="w-4 h-4" />;
        }
        return <AlertCircle className="w-4 h-4" />;
    }

    const AccountCard = ({ account }) => (
        <Card className="bg-white dark:bg-zinc-900 shadow-sm hover:shadow-md border border-gray-200 dark:border-zinc-800 transition-all duration-200 group">
                <CardContent className="p-4 md:p-6">
                    {/* Header */}
                    <div className="flex items-start justify-between mb-4">
                        <div className="flex items-center gap-3 flex-1 min-w-0">
                            <div className="relative flex-shrink-0">
                                <Avatar className="w-10 h-10 md:w-12 md:h-12 border-2 border-white dark:border-zinc-800 shadow-sm">
                                    <AvatarImage
                                        src={account.profile_picture || account.avatar}
                                        alt={account.label || account.name}
                                    />
                                    <AvatarFallback className="bg-gradient-to-br from-primary/20 to-secondary/20 text-primary font-semibold">
                                        {(account.label || account.name || "U").charAt(0).toUpperCase()}
                                    </AvatarFallback>
                                </Avatar>
                                <div className="absolute -bottom-1 -right-1 w-6 h-6 bg-white dark:bg-zinc-900 rounded-full flex items-center justify-center shadow-sm border border-gray-200 dark:border-zinc-800">
                                    <PlatformIcon slug={platform.slug} size={12} />
                                </div>
                            </div>

                            <div className="min-w-0 flex-1">
                                <h3 className="font-semibold text-gray-900 dark:text-gray-100 truncate">
                                    {account.label || account.name || "Unnamed Account"}
                                </h3>
                                {account.username && (
                                    <p className="text-sm text-gray-500 dark:text-gray-400 truncate">
                                        @{account.username}
                                    </p>
                                )}
                                <div className="flex flex-wrap items-center gap-1.5 mt-2.5">
                                    <Badge className={`text-xs border ${getStatusColor(account)}`}>
                                        {getStatusIcon(account)}
                                        <span className="ml-1 hidden sm:inline">
                                            {account.is_connected === "1" ? "Connected" : "Not Connected"}
                                        </span>
                                    </Badge>
                                    {account.account_type !== undefined && (
                                        <Badge variant="outline" className="text-xs">
                                            {account.account_type === 0 ? "Profile" :
                                             account.account_type === 1 ? "Page" : "Group"}
                                        </Badge>
                                    )}
                                </div>
                            </div>
                        </div>

                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-8 w-8 p-0 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity hover:bg-gray-100 dark:hover:bg-zinc-800 flex-shrink-0"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                    }}
                                >
                                    <MoreVertical className="h-4 w-4" />
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent
                                align="end"
                                className="w-48 z-50 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-lg"
                                onClick={(e) => e.stopPropagation()}
                            >
                                {account.is_connected === "1" ? (
                                    <DropdownMenuItem
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            handleViewProfile(account);
                                        }}
                                        className="hover:bg-gray-100 dark:hover:bg-zinc-800 cursor-pointer"
                                    >
                                        <Eye className="h-4 w-4 mr-2" />
                                        View Profile
                                    </DropdownMenuItem>
                                ) : (
                                    <DropdownMenuItem
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            handleConnect(account);
                                        }}
                                        className="hover:bg-gray-100 dark:hover:bg-zinc-800 cursor-pointer"
                                    >
                                        <Link className="h-4 w-4 mr-2" />
                                        Connect Account
                                    </DropdownMenuItem>
                                )}
                                <DropdownMenuItem
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        handleDeleteClick(account);
                                    }}
                                    className="text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 cursor-pointer"
                                >
                                    <Trash2 className="h-4 w-4 mr-2" />
                                    Delete
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </div>

                    {/* Stats - Only show for connected accounts */}
                    {account.is_connected === "1" && (
                        <div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-100 dark:border-zinc-800">
                            <div className="text-center">
                                <div className="flex items-center justify-center gap-1 text-sm font-semibold text-gray-900 dark:text-gray-100">
                                    <Users className="w-4 h-4 text-primary" />
                                    {account.followers || 0}
                                </div>
                                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Followers</p>
                            </div>
                            <div className="text-center border-l border-gray-100 dark:border-zinc-800">
                                <div className="flex items-center justify-center gap-1 text-sm font-semibold text-gray-900 dark:text-gray-100">
                                    <BarChart3 className="w-4 h-4 text-secondary" />
                                    {account.engagement || 0}
                                </div>
                                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Engagement</p>
                            </div>
                            <div className="text-center border-l border-gray-100 dark:border-zinc-800">
                                <div className="flex items-center justify-center gap-1 text-sm font-semibold text-gray-900 dark:text-gray-100">
                                    <Clock className="w-4 h-4 text-amber-500" />
                                    <span className="text-xs">
                                        {account.last_activity || "No activity"}
                                    </span>
                                </div>
                                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Last Activity</p>
                            </div>
                        </div>
                    )}
                </CardContent>
        </Card>
    )

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-zinc-950 dark:to-black">
                <div className="p-6">
                    {/* Header */}
                    <div className="mb-8">
                        <div className="flex items-center gap-4 mb-4">
                            <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => router.get(route("user.platform.index"))}
                                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                            >
                                <ArrowLeft className="w-4 h-4 mr-2" />
                                Back to Platforms
                            </Button>
                        </div>

                        <div className="flex items-center justify-between mb-4">
                            <div className="flex items-center gap-4">
                                <div>
                                    <PlatformIcon slug={platform.slug} size={32} />
                                </div>
                                <div>
                                    <h1 className="text-xl sm:text-2xl font-bold text-gray-900 dark:text-gray-100">
                                        {platform.name} Accounts
                                    </h1>
                                    <p className="text-gray-600 dark:text-gray-400">
                                        Manage your {platform.name} social media accounts and connections
                                    </p>
                                </div>
                            </div> 
                        </div>

                        {/* Stats Summary */}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                            <Card className="bg-white dark:bg-zinc-900 shadow-sm border border-gray-200 dark:border-zinc-800">
                                <CardContent className="p-4">
                                    <div className="flex items-center gap-3">
                                        <div className="p-2 bg-emerald-100 dark:bg-emerald-900/20 rounded-lg">
                                            <CheckCircle className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />
                                        </div>
                                        <div>
                                            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                                {connectedAccounts.length}
                                            </p>
                                            <p className="text-sm text-gray-500 dark:text-gray-400">Connected</p>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>

                            <Card className="bg-white dark:bg-zinc-900 shadow-sm border border-gray-200 dark:border-zinc-800">
                                <CardContent className="p-4">
                                    <div className="flex items-center gap-3">
                                        <div className="p-2 bg-amber-100 dark:bg-amber-900/20 rounded-lg">
                                            <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400" />
                                        </div>
                                        <div>
                                            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                                {disconnectedAccounts.length}
                                            </p>
                                            <p className="text-sm text-gray-500 dark:text-gray-400">Pending Connection</p>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>

                            <Card className="bg-white dark:bg-zinc-900 shadow-sm border border-gray-200 dark:border-zinc-800">
                                <CardContent className="p-4">
                                    <div className="flex items-center gap-3">
                                        <div className="p-2 bg-primary/10 dark:bg-primary/20 rounded-lg">
                                            <Users className="w-5 h-5 text-primary" />
                                        </div>
                                        <div>
                                            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                                {filteredAccounts.length}
                                            </p>
                                            <p className="text-sm text-gray-500 dark:text-gray-400">Total Accounts</p>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        </div>
                    </div>

                    {/* Controls */}
                    <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between mb-6">
                        <div className="relative flex-1 max-w-md">
                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                            <Input
                                type="text"
                                placeholder="Search accounts..."
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="pl-10"
                            />
                        </div>

                        <Button
                            onClick={() => setIsModalOpen(true)}
                            className="bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-sm hover:shadow-md transition-all duration-200"
                        >
                            <Plus className="w-4 h-4 mr-2" />
                            Add {platform.name} Account
                        </Button>
                    </div>

                    {/* Accounts Grid */}
                    {filteredAccounts.length === 0 ? (
                        // Empty State
                        <div className="flex flex-col items-center justify-center py-16 px-4">
                                <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded-full mb-6">
                                    <PlatformIcon slug={platform.slug} size={48} className="opacity-50" />
                                </div>
                                <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">
                                    No {platform.name} Accounts Yet
                                </h3>
                                <p className="text-gray-500 dark:text-gray-400 text-center max-w-md mb-6">
                                    Get started by adding your first {platform.name} account. You can connect multiple accounts to manage different profiles or pages.
                                </p>
                                <Button
                                    onClick={() => setIsModalOpen(true)}
                                    className="bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
                                >
                                    <Plus className="w-4 h-4 mr-2" />
                                    Add Your First Account
                                </Button>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 md:gap-6">
                            {filteredAccounts.map((account) => (
                                <AccountCard key={account.id} account={account} />
                            ))}
                        </div>
                    )}

                    {/* Add Account Modal */}
                    <Modal
                        isOpen={isModalOpen}
                        onClose={() => {
                            setIsModalOpen(false)
                            setFormData({ label: "" })
                        }}
                        title={`Add ${platform.name} Account`}
                        onSubmit={handleCreateAccountLabel}
                        submitText="Create & Connect"
                        isDataSubmitting={isSubmitting}
                        width="w-[28rem]"
                    >
                        <div className="space-y-4">
                            <div className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-zinc-800 rounded-lg">
                                <div className="p-2 bg-white dark:bg-zinc-900 rounded-lg shadow-sm">
                                    <PlatformIcon slug={platform.slug} size={24} />
                                </div>
                                <div>
                                    <h4 className="font-medium text-gray-900 dark:text-gray-100">
                                        {platform.name} Account
                                    </h4>
                                    <p className="text-sm text-gray-500 dark:text-gray-400">
                                        Give your account a memorable name
                                    </p>
                                </div>
                            </div>

                            <div>
                                <Label htmlFor="account-label">
                                    Account Name <span className="text-red-500">*</span>
                                </Label>
                                <Input
                                    id="account-label"
                                    name="label"
                                    type="text"
                                    value={formData.label}
                                    onChange={handleInputChange}
                                    placeholder="e.g., Personal Profile, Business Page, Brand Account"
                                    className="mt-2"
                                    autoFocus
                                />
                                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                    This helps you identify the account in your dashboard
                                </p>
                            </div>

                            <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                                <div className="flex items-start gap-2">
                                    <Zap className="w-4 h-4 text-blue-600 dark:text-blue-400 mt-0.5" />
                                    <div className="flex-1">
                                        <p className="text-sm font-medium text-blue-900 dark:text-blue-300">
                                            Quick Setup
                                        </p>
                                        <p className="text-xs text-blue-700 dark:text-blue-400">
                                            After naming your account, you'll be redirected to {platform.name} to authorize the connection.
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Modal>

                    {/* Profile View Modal */}
                    {profileToShow && (
                        <Modal
                            isOpen={isShowProfileModalOpen}
                            onClose={() => {
                                setIsShowProfileModalOpen(false)
                                setProfileToShow(null)
                            }}
                            title="Account Profile"
                            showSubmit={false}
                            width="w-[32rem]"
                        >
                            <div className="space-y-6">
                                <div className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-zinc-800 rounded-lg">
                                    <Avatar className="w-16 h-16 border-2 border-white dark:border-zinc-800 shadow-sm">
                                        <AvatarImage
                                            src={profileToShow.profile_picture || profileToShow.avatar}
                                            alt={profileToShow.label}
                                        />
                                        <AvatarFallback className="bg-gradient-to-br from-primary/20 to-secondary/20 text-primary font-semibold text-lg">
                                            {(profileToShow.label || "U").charAt(0).toUpperCase()}
                                        </AvatarFallback>
                                    </Avatar>
                                    <div>
                                        <h3 className="font-semibold text-lg text-gray-900 dark:text-gray-100">
                                            {profileToShow.label || profileToShow.name}
                                        </h3>
                                        {profileToShow.username && (
                                            <p className="text-gray-500 dark:text-gray-400">
                                                @{profileToShow.username}
                                            </p>
                                        )}
                                        <Badge className={`mt-2 text-xs border ${getStatusColor(profileToShow)}`}>
                                            {getStatusIcon(profileToShow)}
                                            <span className="ml-1">Connected</span>
                                        </Badge>
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div className="p-4 bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800">
                                        <p className="text-sm text-gray-500 dark:text-gray-400">Followers</p>
                                        <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                            {profileToShow.followers || 0}
                                        </p>
                                    </div>
                                    <div className="p-4 bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800">
                                        <p className="text-sm text-gray-500 dark:text-gray-400">Engagement</p>
                                        <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                            {profileToShow.engagement || 0}
                                        </p>
                                    </div>
                                </div>

                                <div className="space-y-3">
                                    <div className="flex justify-between py-2 border-b border-gray-100 dark:border-zinc-800">
                                        <span className="text-sm text-gray-500 dark:text-gray-400">Account Type</span>
                                        <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {profileToShow.account_type === 0 ? "Profile" :
                                             profileToShow.account_type === 1 ? "Page" : "Group"}
                                        </span>
                                    </div>
                                    <div className="flex justify-between py-2 border-b border-gray-100 dark:border-zinc-800">
                                        <span className="text-sm text-gray-500 dark:text-gray-400">Connected At</span>
                                        <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {profileToShow.created_at ?
                                                new Date(profileToShow.created_at).toLocaleDateString() :
                                                "Unknown"
                                            }
                                        </span>
                                    </div>
                                    <div className="flex justify-between py-2">
                                        <span className="text-sm text-gray-500 dark:text-gray-400">Last Activity</span>
                                        <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {profileToShow.last_activity || "No recent activity"}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </Modal>
                    )}

                    {/* Delete Confirmation Modal */}
                    <DeleteModal
                        isOpen={isDeleteModalOpen}
                        onClose={() => setIsDeleteModalOpen(false)}
                        onConfirm={handleDeleteConfirm}
                        title="Delete Account"
                        description={`Are you sure you want to delete "${accountToDelete?.label || 'this account'}"? This action cannot be undone.`}
                    />

                    {/* Configuration Error Modal */}
                    <Modal
                        isOpen={isConfigErrorModalOpen}
                        onClose={() => {
                            setIsConfigErrorModalOpen(false)
                            setConfigError(null)
                        }}
                        title={`${platform.name} Configuration Required`}
                        showSubmit={false}
                        width="w-[32rem]"
                    >
                        <div className="space-y-6 text-center">
                            <div className="flex flex-col items-center gap-4">
                                <div className="p-4 bg-red-100 dark:bg-red-900/20 rounded-full">
                                    <AlertTriangle className="w-12 h-12 text-red-600 dark:text-red-400" />
                                </div>
                                <div>
                                    <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
                                        Platform Not Configured
                                    </h3>
                                    <p className="text-gray-600 dark:text-gray-400">
                                        {configError?.message}
                                    </p>
                                </div>
                            </div>

                            <div className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-zinc-800 rounded-lg">
                                <div className="p-2 bg-white dark:bg-zinc-900 rounded-lg shadow-sm">
                                    <PlatformIcon slug={platform.slug} size={24} />
                                </div>
                                <div className="text-left">
                                    <p className="font-medium text-gray-900 dark:text-gray-100">
                                        {platform.name}
                                    </p>
                                    <p className="text-sm text-gray-500 dark:text-gray-400">
                                        Requires API Configuration
                                    </p>
                                </div>
                            </div>

                            <div className="p-4 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800">
                                <div className="flex items-start gap-3">
                                    <Settings className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5" />
                                    <div className="text-left flex-1">
                                        <h4 className="text-sm font-medium text-amber-900 dark:text-amber-300 mb-1">
                                            Configuration Required
                                        </h4>
                                        <p className="text-xs text-amber-700 dark:text-amber-400">
                                            To connect {platform.name} accounts, you need to configure API credentials (Client ID, Client Secret, etc.) in the platform settings.
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div className="flex items-center gap-3">
                                <Button
                                    variant="outline"
                                    onClick={() => {
                                        setIsConfigErrorModalOpen(false)
                                        setConfigError(null)
                                    }}
                                    className="flex-1"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    onClick={handleConfigurePlatform}
                                    className="flex-1 bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
                                >
                                    <Settings className="w-4 h-4 mr-2" />
                                    Configure Platform
                                </Button>
                            </div>
                        </div>
                    </Modal>
                </div>
            </div>
        </AppLayout>
    )
}