import React, { ReactNode } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Button } from '@admin/components/ui/button';
import { Badge } from '@admin/components/ui/badge';
import { Head, router } from '@inertiajs/react';
import AdminLayout from '@admin/layouts/admin/admin-layout';
import {
    Briefcase,
    Building2,
    Edit,
    FileText,
    MapPin,
    Package as PackageIcon,
    Settings,
    UserCheck,
    UserCircle,
    ArrowLeft,
} from 'lucide-react';

export interface Package {
    id: number;
    name: string;
    slug?: string;
    description?: string;
    pricing_type?: number;
    price_per_tenant?: string;
    price_per_user?: string;
    status_info?: {
        value: number | null;
        name: string;
    };
}

export interface ContactPerson {
    name?: string;
    email?: string;
    phone?: string;
}

export interface Subscription {
    package?: Package;
    subscription_info?: {
        started_at?: string;
        expires_at?: string;
        status?: string;
    };
}

export interface Tenant {
    id: string;
    name: string;
    email: string;
    phone?: string;
    company_name: string;
    company_email: string;
    company_phone: string;
    address?: string;
    city?: string;
    state?: string;
    country?: string;
    zip_code?: string;
    domain?: string;
    status?: string | number;
    package_id?: number;
    pricing_type?: string;
    subscription?: Subscription;

    // Business Information
    business_type?: string;
    industry?: string;
    tax_id?: string;
    registration_number?: string;

    // Limits & Quotas
    max_users?: number;
    max_storage_mb?: number;
    custom_domain_enabled?: boolean;

    // Contact Persons (Multiple)
    contact_persons?: ContactPerson[];

    // Settings
    timezone?: string;
    language?: string;
    currency?: string;

    // Metadata
    notes?: string;
}

interface TenantViewProps {
    readonly tenant: Tenant;
}

function SelectedPackageInfo({ tenant }: { tenant: Tenant }) {
    const subscription = tenant.subscription;
    const selectedPackage = subscription?.package;

    if (!selectedPackage) {
        return (
            <Card className="border-2 border-gray-200 bg-gray-50">
                <CardContent className="p-5">
                    <p className="text-sm text-gray-500">No package assigned</p>
                </CardContent>
            </Card>
        );
    }

    const pricingType = tenant.pricing_type || '1';
    const displayPrice = pricingType === '1' ? selectedPackage.price_per_tenant : selectedPackage.price_per_user;
    const priceLabel = pricingType === '1' ? 'Per Tenant' : 'Per User';
    const priceValue = displayPrice ? parseFloat(displayPrice) : 0;

    return (
        <Card className="border-2 border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50/50">
            <CardContent className="p-5">
                <div className="flex items-start gap-4">
                    <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-blue-500 to-blue-600 shadow-md">
                        <PackageIcon className="h-6 w-6 text-white" />
                    </div>
                    <div className="flex-1">
                        <p className="text-xs font-medium text-gray-500">Assigned Package</p>
                        <h4 className="mt-1 font-bold text-gray-900">{selectedPackage.name}</h4>
                        <div className="mt-3 flex items-baseline gap-2">
                            <span className="text-3xl font-bold text-blue-600">${priceValue.toFixed(2)}</span>
                            <span className="text-sm font-medium text-gray-500">/ {priceLabel}</span>
                        </div>
                        {selectedPackage.description && <p className="mt-2 text-xs text-gray-600">{selectedPackage.description}</p>}
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

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

    return (
        <div className="space-y-1">
            <label className="text-xs font-medium text-gray-500 uppercase">{label}</label>
            <p className="text-sm font-medium text-gray-900">{typeof value === 'boolean' ? (value ? 'Yes' : 'No') : value}</p>
        </div>
    );
}

function ContactPersonsSection({ contacts }: { contacts?: ContactPerson[] }) {
    if (!contacts || contacts.length === 0) {
        return (
            <div className="text-sm text-gray-500">
                No contact persons registered
            </div>
        );
    }

    return (
        <div className="space-y-4">
            {contacts.map((contact, index) => (
                <Card key={index} className="border-l-4 border-l-indigo-400 bg-white shadow-sm">
                    <CardContent className="p-5">
                        <div className="flex items-start gap-4">
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-indigo-100">
                                <UserCircle className="h-4 w-4 text-indigo-600" />
                            </div>
                            <div className="flex-1 space-y-3">
                                <h4 className="font-semibold text-gray-900">Contact {index + 1}</h4>
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                                    <InfoField label="Name" value={contact.name} />
                                    <InfoField label="Email" value={contact.email} />
                                    <InfoField label="Phone" value={contact.phone} />
                                </div>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            ))}
        </div>
    );
}

function getStatusColor(status?: string | number): string {
    const statusValue = typeof status === 'string' ? parseInt(status) : status;
    switch (statusValue) {
        case 1:
            return 'bg-green-100 text-green-800 border-green-300';
        case 0:
            return 'bg-gray-100 text-gray-800 border-gray-300';
        case 2:
            return 'bg-yellow-100 text-yellow-800 border-yellow-300';
        case 3:
            return 'bg-red-100 text-red-800 border-red-300';
        default:
            return 'bg-gray-100 text-gray-800 border-gray-300';
    }
}

function getStatusLabel(status?: string | number): string {
    const statusValue = typeof status === 'string' ? parseInt(status) : status;
    switch (statusValue) {
        case 1:
            return 'Active';
        case 0:
            return 'Inactive';
        case 2:
            return 'Suspended';
        case 3:
            return 'Pending';
        default:
            return 'Unknown';
    }
}

function TenantView({ tenant }: TenantViewProps) {
    const handleBackToList = () => {
        router.visit(route('admin.tenants.index'));
    };

    const handleEdit = () => {
        router.visit(route('admin.tenants.edit', tenant.id));
    };

    return (
        <>
            <Head title={`View Tenant - ${tenant.name}`} />
            <div className="space-y-6 p-6">
                <Card className="overflow-hidden shadow-xl border-2 border-gray-200">
                    {/* Tenant Header - Sticky */}
                    <div className="sticky top-0 z-10 bg-gradient-to-r from-white via-gray-50 to-white border-b-2 border-gray-200 shadow-md">
                        <div className="flex items-center justify-between p-6">
                            <div className="flex items-center gap-4 flex-1">
                                <div className="p-3 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg">
                                    <Building2 className="h-7 w-7 text-white" />
                                </div>
                                <div>
                                    <div className="flex items-center gap-3 mb-1">
                                        <h2 className="text-2xl font-bold text-gray-900">{tenant.name}</h2>
                                        <Badge className={`${getStatusColor(tenant.status)} border px-3 py-1 font-semibold text-xs`}>
                                            {getStatusLabel(tenant.status)}
                                        </Badge>
                                    </div>
                                    <div className="flex items-center gap-4 text-sm font-medium text-gray-600">
                                        <span className="flex items-center gap-1">
                                            <UserCircle className="h-4 w-4 text-blue-600" />
                                            {tenant.email}
                                        </span>
                                        {tenant.company_name && (
                                            <>
                                                <span className="text-gray-400">|</span>
                                                <span className="flex items-center gap-1">
                                                    <Building2 className="h-4 w-4 text-emerald-600" />
                                                    {tenant.company_name}
                                                </span>
                                            </>
                                        )}
                                        {tenant.domain && (
                                            <>
                                                <span className="text-gray-400">|</span>
                                                <span className="flex items-center gap-1 font-mono text-xs">
                                                    {tenant.domain}
                                                </span>
                                            </>
                                        )}
                                    </div>
                                </div>
                            </div>
                            <div className="flex items-center gap-3">
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={handleEdit}
                                    className="bg-blue-600 text-white hover:bg-blue-700 border-blue-600"
                                >
                                    <Edit className="h-4 w-4 mr-1" />
                                    Edit
                                </Button>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={handleBackToList}
                                    className="bg-white hover:bg-gray-50 border-gray-300"
                                >
                                    <ArrowLeft className="h-4 w-4 mr-1" />
                                    Back to List
                                </Button>
                            </div>
                        </div>
                    </div>

                    {/* Tenant Content */}
                    <CardContent className="p-6 bg-gray-50/50">
                        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                        {/* Left Column - Main Information */}
                        <div className="space-y-6 lg:col-span-2">
                            {/* Admin Access Information */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-blue-50 via-indigo-50 to-blue-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-red-400 p-2.5 shadow-md">
                                            <UserCheck className="h-5 w-5 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Admin Access Information</CardTitle>
                                            <p className="text-xs text-gray-600">
                                                Essential credentials and configuration details
                                            </p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="p-6">
                                    <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                                        <InfoField label="Name" value={tenant.name} />
                                        <InfoField label="Email" value={tenant.email} />
                                        <InfoField label="Phone Number" value={tenant.phone} />
                                        <InfoField label="Domain Name" value={tenant.domain} />
                                        <div className="space-y-1">
                                            <label className="text-xs font-medium text-gray-500 uppercase">Status</label>
                                            <div>
                                                <Badge className={`${getStatusColor(tenant.status)} border px-3 py-1`}>
                                                    {getStatusLabel(tenant.status)}
                                                </Badge>
                                            </div>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Basic Information */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-blue-50 via-indigo-50 to-blue-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-blue-500 p-2.5 shadow-md">
                                            <Building2 className="h-5 w-5 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Company Information</CardTitle>
                                            <p className="text-xs text-gray-600">Essential company details</p>
                                        </div>
                                    </div>
                                </CardHeader>

                                <CardContent className="p-6">
                                    <div className="space-y-8">
                                        {/* Basic Info Group */}
                                        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                                            <InfoField label="Company Name" value={tenant.company_name} />
                                            <InfoField label="Email Address" value={tenant.company_email} />
                                            <InfoField label="Phone Number" value={tenant.company_phone} />
                                        </div>

                                        {/* Business Info Group */}
                                        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                                            <InfoField label="Business Type" value={tenant.business_type} />
                                            <InfoField label="Industry" value={tenant.industry} />
                                            <InfoField label="Tax ID / EIN" value={tenant.tax_id} />
                                            <InfoField label="Registration Number" value={tenant.registration_number} />
                                        </div>

                                        {/* Address Group */}
                                        {tenant.address && (
                                            <div className="grid grid-cols-1 gap-6">
                                                <InfoField label="Address" value={tenant.address} />
                                            </div>
                                        )}
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Contact Persons */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-indigo-50 via-purple-50 to-indigo-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-indigo-500 p-2.5 shadow-md">
                                            <UserCircle className="h-5 w-5 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Contact Persons</CardTitle>
                                            <p className="text-xs text-gray-600">Primary contacts for this tenant</p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="p-6">
                                    <ContactPersonsSection contacts={tenant.contact_persons} />
                                </CardContent>
                            </Card>
                        </div>

                        {/* Right Column - Package & Settings */}
                        <div className="space-y-6">
                            {/* Package Assignment */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-blue-50 via-cyan-50 to-blue-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-cyan-500 p-2.5 shadow-md">
                                            <PackageIcon className="h-5 w-5 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Package</CardTitle>
                                            <p className="text-xs text-gray-600">Subscription plan</p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-5 p-6">
                                    <SelectedPackageInfo tenant={tenant} />
                                    
                                    {tenant.subscription?.subscription_info && (
                                        <div className="space-y-3 rounded-lg border bg-gray-50 p-4">
                                            <InfoField label="Started At" value={tenant.subscription.subscription_info.started_at} />
                                            <InfoField label="Expires At" value={tenant.subscription.subscription_info.expires_at} />
                                        </div>
                                    )}
                                </CardContent>
                            </Card>

                            {/* Limits & Quotas */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-purple-50 via-pink-50 to-purple-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-purple-500 p-2.5 shadow-md">
                                            <Briefcase className="h-5 w-5 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Limits & Quotas</CardTitle>
                                            <p className="text-xs text-gray-600">Resource allocation</p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-5 p-6">
                                    <InfoField label="Max Users" value={tenant.max_users} />
                                    <InfoField label="Max Storage (MB)" value={tenant.max_storage_mb} />
                                    <InfoField label="Custom Domain Enabled" value={tenant.custom_domain_enabled} />
                                </CardContent>
                            </Card>

                            {/* Settings */}
                            <Card className="overflow-hidden border-0 shadow-lg">
                                <CardHeader className="border-b bg-gradient-to-r from-green-50 via-emerald-50 to-green-50 px-6 py-5">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-xl bg-green-500 p-2.5 shadow-md">
                                            <Settings className="h-5 w-5 text-white" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-lg font-bold text-gray-900">Settings</CardTitle>
                                            <p className="text-xs text-gray-600">Regional preferences</p>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-5 p-6">
                                    <InfoField label="Timezone" value={tenant.timezone} />
                                    <InfoField label="Language" value={tenant.language} />
                                    <InfoField label="Currency" value={tenant.currency} />
                                </CardContent>
                            </Card>

                            {/* Additional Notes */}
                            {tenant.notes && (
                                <Card className="overflow-hidden border-0 shadow-lg">
                                    <CardHeader className="border-b bg-gradient-to-r from-amber-50 via-yellow-50 to-amber-50 px-6 py-5">
                                        <div className="flex items-center gap-3">
                                            <div className="rounded-xl bg-amber-500 p-2.5 shadow-md">
                                                <FileText className="h-5 w-5 text-white" />
                                            </div>
                                            <div>
                                                <CardTitle className="text-lg font-bold text-gray-900">Additional Notes</CardTitle>
                                                <p className="text-xs text-gray-600">Internal notes and comments</p>
                                            </div>
                                        </div>
                                    </CardHeader>
                                    <CardContent className="p-6">
                                        <p className="text-sm text-gray-700 whitespace-pre-wrap">{tenant.notes}</p>
                                    </CardContent>
                                </Card>
                            )}
                        </div>
                    </div>
                </CardContent>
            </Card>
        </div>
        </>
    );
}

export default TenantView;

TenantView.layout = (page: ReactNode) => (
    <AdminLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Tenants', href: route('admin.tenants.index') },
            { title: 'View Details', href: '#' },
        ]}
    >
        {page}
    </AdminLayout>
);
