import { Head, router } from '@inertiajs/react';
import { useState } from 'react';
import PartnerLayout from '@/components/Layouts/PartnerLayout';
import Card from '@/components/Card/Card';
import Button from '@/components/Button/Button';
import Modal from '@/components/Modal/Modal';
import { usePage } from '@inertiajs/react';
import { User } from '@/types';

interface ApiKeyPageProps {
    apiKey: {
        id: number;
        name: string;
        key: string;
        last_used_at?: string;
        expires_at?: string;
        is_active: boolean;
        created_at: string;
    } | null;
}

export default function ApiKey() {
    const { props } = usePage();
    const auth = (props as any).auth;
    const user = auth?.user as User;
    const apiKey = (props as any).apiKey as ApiKeyPageProps['apiKey'];

    const [isRegenerateModalOpen, setIsRegenerateModalOpen] = useState(false);
    const [isRevokeModalOpen, setIsRevokeModalOpen] = useState(false);
    const [showApiKey, setShowApiKey] = useState(false);

    const handleGenerate = () => {
        router.post('/partner/api-key', {}, {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {
                setShowApiKey(true);
            },
        });
    };

    const handleRegenerate = () => {
        router.post('/partner/api-key/regenerate', {}, {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {
                setIsRegenerateModalOpen(false);
                setShowApiKey(true);
            },
        });
    };

    const handleRevoke = () => {
        if (!apiKey) {
            return;
        }

        router.delete(`/partner/api-key/${apiKey.id}`, {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {
                setIsRevokeModalOpen(false);
            },
        });
    };

    const copyToClipboard = (text: string) => {
        navigator.clipboard.writeText(text).then(() => {
            // You can add a toast notification here
        });
    };

    const formatDate = (dateString?: string) => {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleString('id-ID', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    // Check if user has api_access feature
    const hasApiAccess = user.features?.includes('api_access');

    if (!hasApiAccess) {
        return (
            <PartnerLayout title="API Key">
                <Head title="API Key" />
                <Card padding="md">
                    <div className="text-center py-8">
                        <i className="fas fa-lock text-4xl text-gray-400 dark:text-gray-500 mb-4"></i>
                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                            API Access Tidak Tersedia
                        </h3>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                            Fitur API Access belum diaktifkan untuk akun Anda. Silakan hubungi administrator untuk mengaktifkan fitur ini.
                        </p>
                    </div>
                </Card>
            </PartnerLayout>
        );
    }

    return (
        <PartnerLayout title="API Key">
            <Head title="API Key" />
            <div className="space-y-6">
                {/* Header */}
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 dark:text-white">API Key Management</h1>
                    <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                        Kelola API key untuk mengakses API partner shows
                    </p>
                </div>

                {/* API Key Card */}
                <Card padding="md">
                    {!apiKey ? (
                        <div className="text-center py-8">
                            <i className="fas fa-key text-4xl text-gray-400 dark:text-gray-500 mb-4"></i>
                            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                                Belum Ada API Key
                            </h3>
                            <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
                                Generate API key untuk mulai menggunakan API partner shows. Maksimal 1 API key per partner.
                            </p>
                            <Button onClick={handleGenerate}>
                                <i className="fas fa-plus mr-2"></i>
                                Generate API Key
                            </Button>
                        </div>
                    ) : (
                        <div className="space-y-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                    API Key
                                </label>
                                <div className="flex items-center gap-2">
                                    <div className="flex-1 relative">
                                        <input
                                            type={showApiKey ? 'text' : 'password'}
                                            value={apiKey.key}
                                            readOnly
                                            className="block w-full rounded-md border-gray-300 bg-gray-50 pr-10 font-mono text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                        />
                                        <button
                                            onClick={() => setShowApiKey(!showApiKey)}
                                            className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                                        >
                                            <i className={`fas ${showApiKey ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                                        </button>
                                    </div>
                                    <Button
                                        variant="secondary"
                                        onClick={() => copyToClipboard(apiKey.key)}
                                    >
                                        <i className="fas fa-copy mr-2"></i>
                                        Copy
                                    </Button>
                                </div>
                                <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                                    <i className="fas fa-info-circle mr-1"></i>
                                    Simpan API key ini dengan aman. Key ini tidak akan ditampilkan lagi setelah halaman ini ditutup.
                                </p>
                            </div>

                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Nama
                                    </label>
                                    <p className="text-sm text-gray-900 dark:text-white">{apiKey.name}</p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Status
                                    </label>
                                    <span
                                        className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${
                                            apiKey.is_active
                                                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                                                : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
                                        }`}
                                    >
                                        {apiKey.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Dibuat
                                    </label>
                                    <p className="text-sm text-gray-900 dark:text-white">
                                        {formatDate(apiKey.created_at)}
                                    </p>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Terakhir Digunakan
                                    </label>
                                    <p className="text-sm text-gray-900 dark:text-white">
                                        {formatDate(apiKey.last_used_at)}
                                    </p>
                                </div>
                            </div>

                            <div className="flex gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
                                <Button
                                    variant="secondary"
                                    onClick={() => setIsRegenerateModalOpen(true)}
                                >
                                    <i className="fas fa-sync mr-2"></i>
                                    Regenerate
                                </Button>
                                <Button
                                    variant="danger"
                                    onClick={() => setIsRevokeModalOpen(true)}
                                >
                                    <i className="fas fa-ban mr-2"></i>
                                    Revoke
                                </Button>
                            </div>
                        </div>
                    )}
                </Card>

                {/* API Documentation Link */}
                <Card padding="md">
                    <div className="flex items-center justify-between">
                        <div>
                            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                                <i className="fas fa-book mr-2"></i>
                                API Documentation
                            </h2>
                            <p className="text-sm text-gray-600 dark:text-gray-400">
                                Lihat dokumentasi lengkap untuk semua endpoint API
                            </p>
                        </div>
                        <a
                            href="/partner/api-docs"
                            className="px-4 py-2 bg-[#d4af37] hover:bg-[#b8941f] text-white rounded-md transition-colors"
                        >
                            <i className="fas fa-external-link-alt mr-2"></i>
                            Buka Dokumentasi
                        </a>
                    </div>
                </Card>

                {/* Regenerate Modal */}
                <Modal
                    isOpen={isRegenerateModalOpen}
                    onClose={() => setIsRegenerateModalOpen(false)}
                    title="Regenerate API Key"
                    size="sm"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => setIsRegenerateModalOpen(false)}
                            >
                                Batal
                            </Button>
                            <Button variant="danger" onClick={handleRegenerate}>
                                Regenerate
                            </Button>
                        </div>
                    }
                >
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                        Apakah Anda yakin ingin regenerate API key? Key lama akan dinonaktifkan dan tidak dapat digunakan lagi.
                    </p>
                </Modal>

                {/* Revoke Modal */}
                <Modal
                    isOpen={isRevokeModalOpen}
                    onClose={() => setIsRevokeModalOpen(false)}
                    title="Revoke API Key"
                    size="sm"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => setIsRevokeModalOpen(false)}
                            >
                                Batal
                            </Button>
                            <Button variant="danger" onClick={handleRevoke}>
                                Revoke
                            </Button>
                        </div>
                    }
                >
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                        Apakah Anda yakin ingin revoke API key ini? Key akan dinonaktifkan dan tidak dapat digunakan lagi.
                    </p>
                </Modal>
            </div>
        </PartnerLayout>
    );
}

