'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { packagesApi } from '@/lib/api/packages';
import PackageList from '@/components/admin/packages/PackageList';
import PackageForm from '@/components/admin/packages/PackageForm';
import PageHeader from '@/components/admin/PageHeader';
import { showToast } from '@/components/Toast';
import { PackageName, CreatePackageData, UpdatePackageData } from '@/types/package';
import { PlusIcon } from '@heroicons/react/24/outline';

export default function PackagesPage() {
    const { token } = useAuth();
    const [packages, setPackages] = useState<PackageName[]>([]);
    const [selectedPackage, setSelectedPackage] = useState<PackageName | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isFormVisible, setIsFormVisible] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (token) {
            loadPackages();
        }
    }, [token]);

    const loadPackages = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const data = await packagesApi.getAllPackages(token!);
            setPackages(data);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در دریافت لیست پکیج‌ها');
        } finally {
            setIsLoading(false);
        }
    };

    const handleCreate = () => {
        setSelectedPackage(null);
        setIsFormVisible(true);
    };

    const handleEdit = (pkg: PackageName) => {
        setSelectedPackage(pkg);
        setIsFormVisible(true);
    };

    const handleDelete = async (pkg: PackageName) => {
        if (!confirm(`آیا از حذف پکیج "${pkg.title}" اطمینان دارید؟`)) {
            return;
        }

        setIsLoading(true);
        setError(null);

        try {
            await packagesApi.deletePackage(pkg.name!, token!);
            showToast('success', 'پکیج با موفقیت حذف شد');
            await loadPackages();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در حذف پکیج');
        } finally {
            setIsLoading(false);
        }
    };

    const handleSubmit = async (data: CreatePackageData | UpdatePackageData) => {
        setIsLoading(true);
        setError(null);

        try {
            if (selectedPackage) {
                await packagesApi.updatePackage(selectedPackage.name!, data, token!);
                showToast('success', 'پکیج با موفقیت به‌روزرسانی شد');
            } else {
                await packagesApi.createPackage(data as CreatePackageData, token!);
                showToast('success', 'پکیج با موفقیت ایجاد شد');
            }

            await loadPackages();
            setIsFormVisible(false);
            setSelectedPackage(null);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در ذخیره پکیج');
        } finally {
            setIsLoading(false);
        }
    };

    const handleCancel = () => {
        setIsFormVisible(false);
        setSelectedPackage(null);
        setError(null);
    };

    return (
        <div className="p-4 sm:p-8">
            <div className="max-w-7xl mx-auto">
                <PageHeader
                    title="مدیریت پکیج‌ها"
                    action={
                        !isFormVisible ? (
                            <button
                                onClick={handleCreate}
                                className="inline-flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 transition-colors shadow-sm shadow-indigo-500/20"
                            >
                                <PlusIcon className="h-4 w-4" />
                                پکیج جدید
                            </button>
                        ) : undefined
                    }
                />

                {error && (
                    <div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
                        <p className="text-sm text-red-700 dark:text-red-300">{error}</p>
                        <button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
                            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                )}

                {isFormVisible ? (
                    <PackageForm
                        package={selectedPackage}
                        onSubmit={handleSubmit}
                        onCancel={handleCancel}
                        isLoading={isLoading}
                    />
                ) : (
                    <PackageList
                        packages={packages}
                        onEdit={handleEdit}
                        onDelete={handleDelete}
                        isLoading={isLoading}
                    />
                )}
            </div>
        </div>
    );
}
