import React, { useEffect, useRef, useState } from 'react';
import Form from '@admin/components/form/Form';
import FormField from '@admin/components/form/FormField';
import { Alert, AlertDescription } from '@admin/components/ui/alert';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Input } from '@admin/components/ui/input';
import { Label } from '@admin/components/ui/label';
import { cn } from '@admin/lib/utils';
import { zodResolver } from '@hookform/resolvers/zod';
import { Head, router } from '@inertiajs/react';
import {
    Building2,
    CheckCircle,
    ChevronDown,
    ChevronUp,
    FileText,
    Globe,
    Loader2,
    MapPin,
    Plus,
    Save,
    Settings,
    Trash2,
    UserCheck,
    UserCircle,
    XCircle,
} from 'lucide-react';
import { Controller, useFieldArray, useFormContext, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';

const tenantSchema = z.object({
    // Core Tenant Information
    name: z.string().min(1, 'Tenant name is required'),
    email: z.string().email('Invalid email address'),
    password: z.string().min(8, 'Password must be at least 8 characters').or(z.literal('')),
    phone: z.string().optional(),
    company_name: z.string().min(1, 'Company name is required'),
    company_email: z.string().email('Invalid company email address').optional(),
    company_phone: z.string().optional(),
    address: z.string().optional(),
    city: z.string().optional(),
    state: z.string().optional(),
    country: z.string().optional(),
    zip_code: z.string().optional(),
    domain: z.string().optional(),
    status: z.string().min(1, 'Status is required'),

    // Business Information
    business_type: z.string().optional(),
    industry: z.string().optional(),
    tax_id: z.string().optional(),
    registration_number: z.string().optional(),

    // Limits & Quotas
    max_users: z.string().optional(),
    max_storage_mb: z.string().optional(),
    custom_domain_enabled: z.boolean().optional(),

    // Contact Persons (Multiple)
    contact_persons: z
        .array(
            z.object({
                name: z.string().optional(),
                email: z.string().email('Invalid email address').optional().or(z.literal('')),
                phone: z.string().optional(),
            }),
        )
        .optional(),

    // Settings
    timezone: z.string().optional(),
    language: z.string().optional(),
    currency: z.string().optional(),

    // Metadata
    notes: z.string().optional(),

    // Domains (Multiple)
    domains: z
        .array(
            z.object({
                id: z.number().optional(),
                domain: z.string().min(1, 'Domain name is required'),
                is_primary: z.boolean().optional(),
                is_custom: z.boolean().optional(),
                status: z.string().optional(),
                ssl_config: z
                    .object({
                        ssl_enabled: z.boolean().optional(),
                        ssl_expires_at: z.string().optional(),
                        ssl_provider: z.string().optional(),
                        ssl_certificate: z.string().optional(),
                        ssl_private_key: z.string().optional(),
                        ssl_chain: z.string().optional(),
                    })
                    .optional(),
                dns_records: z
                    .object({
                        dns_status: z.enum(['verified', 'pending', 'failed']).optional(),
                        dns_verified_at: z.string().optional(),
                        nameserver_1: z.string().optional(),
                        nameserver_2: z.string().optional(),
                    })
                    .optional(),
                redirect_settings: z
                    .object({
                        redirect_to: z.string().optional(),
                        force_https: z.boolean().optional(),
                        redirect_type: z.string().optional(),
                        redirect_enabled: z.boolean().optional(),
                    })
                    .optional(),
            }),
        )
        .optional(),
});

export type TenantFormData = z.infer<typeof tenantSchema>;

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 Tenant {
    id: string;
    tenant_admin_info?: {
        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;

    // 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 TenantFormProps {
    readonly tenant?: Tenant;
    readonly packages?: Package[];
    readonly error?: string;
    readonly errors?: Record<string, string>;
    readonly isEdit?: boolean;
}

function CompanyInfoSection() {
    const [showMore, setShowMore] = useState(false);

    return (
        <div className="space-y-6">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                <FormField name="company_name" type="text" label="Company Name" placeholder="Enter company name" required />
                <FormField name="company_email" type="email" label="Email Address" placeholder="contact@demo.com" required />
                <FormField name="company_phone" type="tel" label="Phone Number" placeholder="+1 (555) 000-0000" />
            </div>

            <button
                type="button"
                onClick={() => setShowMore((v) => !v)}
                className="flex items-center gap-1.5 text-sm font-medium text-blue-600 hover:text-blue-700"
            >
                {showMore ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                {showMore ? 'Less info' : 'More info'}
            </button>

            {showMore && (
                <div className="space-y-6 border-t pt-6">
                    <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                        <FormField name="business_type" type="text" label="Business Type" placeholder="LLC, Corp, Partnership" />
                        <FormField name="industry" type="text" label="Industry" placeholder="Technology, Finance, Healthcare" />
                        <FormField name="tax_id" type="text" label="Tax ID / EIN" placeholder="XX-XXXXXXX" />
                        <FormField name="registration_number" type="text" label="Registration Number" placeholder="Business reg #" />
                    </div>
                    <FormField name="address" type="textarea" label="Address" placeholder="Enter address" />
                </div>
            )}
        </div>
    );
}

type DomainCheckState = 'idle' | 'checking' | 'available' | 'taken' | 'invalid';

interface DomainCheckResult {
    available: boolean;
    domain: string;
    admin_domain: string;
    message: string;
}

function DomainAvailabilityField({ excludeTenantId, initialDomain }: { excludeTenantId?: string | number; initialDomain?: string }) {
    const { control, formState: { errors } } = useFormContext<TenantFormData>();
    const domainValue = useWatch({ control, name: 'domain' });
    const [state, setState] = useState<DomainCheckState>('idle');
    const [result, setResult] = useState<DomainCheckResult | null>(null);
    const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

    useEffect(() => {
        if (debounceRef.current) clearTimeout(debounceRef.current);

        const value = (domainValue || '').trim();

        if (!value || value === initialDomain) {
            setState('idle');
            setResult(null);
            return;
        }

        setState('checking');

        debounceRef.current = setTimeout(async () => {
            try {
                const params = new URLSearchParams({ domain: value });
                if (excludeTenantId) params.set('exclude_id', String(excludeTenantId));
                const url = route('admin.tenants.check-domain') + '?' + params.toString();
                const response = await fetch(url, { headers: { Accept: 'application/json' } });
                const data: DomainCheckResult & { message: string } = await response.json();

                if (!response.ok) {
                    setState('invalid');
                    setResult(null);
                    return;
                }

                setResult(data);
                setState(data.available ? 'available' : 'taken');
            } catch {
                setState('idle');
                setResult(null);
            }
        }, 500);

        return () => {
            if (debounceRef.current) clearTimeout(debounceRef.current);
        };
    }, [domainValue]);

    const errorMessage = errors.domain?.message as string | undefined;

    return (
        <div className="space-y-1">
            <Label className="text-md mb-2 block text-sm text-primary">
                Domain Name <span className="ml-1 text-red-500">*</span>
            </Label>
            <div className="relative">
                <Controller
                    control={control}
                    name="domain"
                    render={({ field }) => (
                        <Input
                            {...field}
                            type="text"
                            placeholder="e.g. acme"
                            value={field.value || ''}
                            className={cn(
                                'pr-9',
                                state === 'available' && 'border-green-400 focus-visible:ring-green-300',
                                state === 'taken' && 'border-red-400 focus-visible:ring-red-300',
                                state === 'invalid' && 'border-yellow-400 focus-visible:ring-yellow-300',
                            )}
                        />
                    )}
                />
                <div className="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                    {state === 'checking' && <Loader2 className="h-4 w-4 animate-spin text-gray-400" />}
                    {state === 'available' && <CheckCircle className="h-4 w-4 text-green-500" />}
                    {state === 'taken' && <XCircle className="h-4 w-4 text-red-500" />}
                    {state === 'invalid' && <XCircle className="h-4 w-4 text-yellow-500" />}
                </div>
            </div>

            {/* Domain preview */}
            {result && state !== 'invalid' && (
                <div className={cn(
                    'mt-2 rounded-md border px-3 py-2 text-xs',
                    state === 'available'
                        ? 'border-green-200 bg-green-50 text-green-700'
                        : 'border-red-200 bg-red-50 text-red-700',
                )}>
                    <div className="mb-1 flex items-center gap-1.5 font-medium">
                        {state === 'available' ? (
                            <CheckCircle className="h-3.5 w-3.5 shrink-0" />
                        ) : (
                            <XCircle className="h-3.5 w-3.5 shrink-0" />
                        )}
                        {result.message}
                    </div>
                    {state === 'available' && (
                        <div className="space-y-0.5 pl-5">
                            <div className="flex items-center gap-1">
                                <Globe className="h-3 w-3 shrink-0 opacity-60" />
                                <span className="font-mono">{result.domain}</span>
                            </div>
                            <div className="flex items-center gap-1">
                                <Globe className="h-3 w-3 shrink-0 opacity-60" />
                                <span className="font-mono">{result.admin_domain}</span>
                                <span className="opacity-60">(admin)</span>
                            </div>
                        </div>
                    )}
                </div>
            )}

            {state === 'invalid' && (
                <p className="mt-1 text-xs text-yellow-600">Only lowercase letters, numbers and hyphens allowed</p>
            )}

            {errorMessage && <small className="mt-1 block text-sm text-red-500">{errorMessage}</small>}
        </div>
    );
}

function ContactPersonsSection() {
    const { control, watch, setValue } = useFormContext<TenantFormData>();
    const { fields, append, remove } = useFieldArray({
        control,
        name: 'contact_persons',
    });

    // Sync first contact with admin info
    const adminName = watch('name');
    const adminEmail = watch('email');
    const adminPhone = watch('phone');
    React.useEffect(() => {
        // Only update if the first contact is empty or matches previous admin info
        setValue('contact_persons.0.name', adminName, { shouldValidate: false });
        setValue('contact_persons.0.email', adminEmail, { shouldValidate: false });
        setValue('contact_persons.0.phone', adminPhone, { shouldValidate: false });
    }, [adminName, adminEmail, adminPhone, setValue]);

    return (
        <div className="space-y-4">
            {fields.map((field, index) => (
                <Card key={field.id} className="border-l-4 border-l-indigo-400 bg-white shadow-sm">
                    <CardContent className="p-5">
                        <div className="flex items-start justify-between gap-4">
                            <div className="flex-1 space-y-4">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        <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>
                                        <h4 className="font-semibold text-gray-900">Contact {index + 1}</h4>
                                    </div>
                                    {fields.length > 1 && (
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => index !== 0 && remove(index)}
                                            className="h-8 text-red-600 hover:bg-red-50 hover:text-red-700"
                                            disabled={index === 0}
                                        >
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    )}
                                </div>
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                                    <FormField name={`contact_persons.${index}.name`} type="text" label="Name" placeholder="John Doe" disabled={index === 0} />
                                    <FormField name={`contact_persons.${index}.email`} type="email" label="Email" placeholder="contact@example.com" disabled={index === 0} />
                                    <FormField name={`contact_persons.${index}.phone`} type="tel" label="Phone" placeholder="+1 (555) 123-4567" disabled={index === 0} />
                                </div>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            ))}

            <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => append({ name: '', email: '', phone: '' })}
                className="w-full border-2 border-dashed border-gray-300 hover:border-indigo-400 hover:bg-indigo-50"
            >
                <Plus className="mr-2 h-4 w-4" />
                Add Contact Person
            </Button>
        </div>
    );
}

export default function TenantForm({ tenant, packages, error, errors: serverErrors, isEdit = false }: TenantFormProps) {
    const defaultValues: Partial<TenantFormData> = {
        name: tenant?.tenant_admin_info?.name || '',
        email: tenant?.tenant_admin_info?.email || '',
        password: '',
        phone: tenant?.tenant_admin_info?.phone || '',
        company_name: tenant?.company_name || '',
        company_email: tenant?.company_email || '',
        company_phone: tenant?.company_phone || '',
        address: tenant?.address || '',
        city: tenant?.city || '',
        state: tenant?.state || '',
        country: tenant?.country || '',
        zip_code: tenant?.zip_code || '',
        domain: tenant?.domain ? tenant.domain.split('.')[0] : '',
        status: tenant?.status?.toString() || '0',
        business_type: tenant?.business_type || '',
        industry: tenant?.industry || '',
        tax_id: tenant?.tax_id || '',
        registration_number: tenant?.registration_number || '',
        max_users: tenant?.max_users?.toString() || '10',
        max_storage_mb: tenant?.max_storage_mb?.toString() || '1000',
        custom_domain_enabled: tenant?.custom_domain_enabled || false,
        contact_persons: tenant?.contact_persons && tenant.contact_persons.length > 0
            ? [
                // First contact synced with admin info
                {
                    name: tenant?.tenant_admin_info?.name || '',
                    email: tenant?.tenant_admin_info?.email || '',
                    phone: tenant?.tenant_admin_info?.phone || ''
                },
                // Additional contacts
                ...tenant.contact_persons.slice(1)
            ]
            : [{
                name: tenant?.tenant_admin_info?.name || '',
                email: tenant?.tenant_admin_info?.email || '',
                phone: tenant?.tenant_admin_info?.phone || ''
            }],
        timezone: tenant?.timezone || 'UTC',
        language: tenant?.language || 'en',
        currency: tenant?.currency || 'USD',
        notes: tenant?.notes || '',
    };

    const handleSubmit = (data: TenantFormData) => {
        // Send flat structure directly
        const payload: any = {
            name: data.name,
            email: data.email,
            phone: data.phone,
            company_name: data.company_name,
            company_email: data.company_email,
            company_phone: data.company_phone,
            domain: data.domain,
            status: parseInt(data.status) || 0,
            // Address fields (flat)
            address: data.address,
            city: data.city,
            state: data.state,
            country: data.country,
            zip_code: data.zip_code,
            // Business information (flat)
            business_type: data.business_type,
            industry: data.industry,
            tax_id: data.tax_id,
            registration_number: data.registration_number,
            // Limits (flat)
            max_users: parseInt(data.max_users as string) || 10,
            max_storage_mb: parseInt(data.max_storage_mb as string) || 1000,
            custom_domain_enabled: data.custom_domain_enabled,
            // Contacts (flat array)
            contact_persons: data.contact_persons,
            // Settings (flat)
            timezone: data.timezone,
            language: data.language,
            currency: data.currency,
            // Metadata (flat)
            notes: data.notes,
        };

        // Only include password if it's provided (not empty)
        if (data.password && data.password.trim() !== '') {
            payload.password = data.password;
        }

        if (isEdit && tenant) {
            router.put(`/admin/tenants/${tenant.id}`, payload, {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success('Tenant updated successfully');
                },
                onError: (errors) => {
                    console.error('Failed to update tenant:', errors);
                    toast.error('Failed to update tenant');
                },
            });
        } else {
            router.post('/admin/tenants', payload, {
                preserveScroll: true,
                onSuccess: () => {
                    toast.success('Tenant created successfully');
                },
                onError: (errors) => {
                    console.error('Failed to create tenant:', errors);
                    toast.error('Failed to create tenant');
                },
            });
        }
    };

    return (
        <>
            <Head title={isEdit ? 'Edit Tenant' : 'Create Tenant'} />
            {error && (
                <div className="mb-6">
                    <Alert variant="destructive">
                        <AlertDescription>{error}</AlertDescription>
                    </Alert>
                </div>
            )}

            <div className="space-y-6">
                    <Form
                        id="tenant-form"
                        submitHandler={handleSubmit}
                        defaultValues={defaultValues}
                        resolver={zodResolver(tenantSchema)}
                        externalErrors={serverErrors}
                    >
                        <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 needed to access and manage the application’s
                                                    administrative panel securely.
                                                </p>
                                            </div>
                                        </div>
                                    </CardHeader>
                                    <CardContent className="p-6">
                                        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                                            <FormField name="name" type="text" label="Name" placeholder="Enter admin name" required />
                                            <FormField name="email" type="email" label="Email" placeholder="contact@acme.com" required />
                                            <FormField name="password" type="password" label="Password" placeholder="Enter admin password" required />
                                            <FormField name="phone" type="tel" label="Phone Number" placeholder="+1 (555) 000-0000" />

                                        </div>
                                    </CardContent>
                                </Card>

                                {/* Domain Setup */}
                                <Card className="overflow-hidden border-0 shadow-lg">
                                    <CardHeader className="border-b bg-gradient-to-r from-purple-50 via-violet-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">
                                                <MapPin className="h-5 w-5 text-white" />
                                            </div>
                                            <div>
                                                <CardTitle className="text-lg font-bold text-gray-900">Domain Setup</CardTitle>
                                                <p className="text-xs text-gray-600">
                                                    Configure the domain settings for this tenant
                                                </p>
                                            </div>
                                        </div>
                                    </CardHeader>
                                    <CardContent className="p-6">
                                        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                                            <DomainAvailabilityField
                                                excludeTenantId={isEdit ? tenant?.id : undefined}
                                                initialDomain={isEdit && tenant?.domain ? tenant.domain.split('.')[0] : undefined}
                                            />
                                        </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">
                                        <CompanyInfoSection />
                                    </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 />
                                    </CardContent>
                                </Card>
                            </div>

                            {/* Right Column - Settings */}
                            <div className="space-y-6">
                                <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">
                                                <CheckCircle className="h-5 w-5 text-white" />
                                            </div>
                                            <div>
                                                <CardTitle className="text-lg font-bold text-gray-900">Status</CardTitle>
                                                <p className="text-xs text-gray-600">Tenant status</p>
                                            </div>
                                        </div>
                                    </CardHeader>
                                    <CardContent className="space-y-5 p-6">
                                        <FormField
                                            name="status"
                                            type="select"
                                            label="Tenant Status"
                                            required
                                            options={[
                                                { value: '0', label: 'Inactive' },
                                                { value: '1', label: 'Active' },
                                                { value: '23', label: 'Creation Initialized' },
                                                { value: '24', label: 'Created' },
                                                { value: '7', label: 'Failed' },
                                            ]}
                                        />
                                    </CardContent>
                                </Card>

                                <Card className="overflow-hidden border-0 shadow-lg">
                                    <CardHeader className="border-b bg-gradient-to-r from-slate-50 via-gray-100 to-slate-50 px-6 py-5">
                                        <div className="flex items-center gap-3">
                                            <div className="rounded-xl bg-slate-600 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">
                                        <FormField
                                            name="timezone"
                                            type="select"
                                            label="Timezone"
                                            options={[
                                                { value: 'UTC', label: 'UTC' },
                                                { value: 'America/New_York', label: 'Eastern (US)' },
                                                { value: 'America/Chicago', label: 'Central (US)' },
                                                { value: 'America/Los_Angeles', label: 'Pacific (US)' },
                                                { value: 'Europe/London', label: 'London' },
                                                { value: 'Asia/Tokyo', label: 'Tokyo' },
                                            ]}
                                        />
                                        <FormField
                                            name="language"
                                            type="select"
                                            label="Language"
                                            options={[
                                                { value: 'en', label: 'English' },
                                                { value: 'es', label: 'Spanish' },
                                                { value: 'fr', label: 'French' },
                                            ]}
                                        />
                                        <FormField
                                            name="currency"
                                            type="select"
                                            label="Currency"
                                            options={[
                                                { value: 'USD', label: 'USD ($)' },
                                                { value: 'EUR', label: 'EUR (€)' },
                                                { value: 'GBP', label: 'GBP (£)' },
                                            ]}
                                        />
                                    </CardContent>
                                </Card>

                                {/* Additional 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">
                                        <FormField name="notes" type="textarea" label="Notes" placeholder="Add any relevant notes..." rows={4} />
                                    </CardContent>
                                </Card>
                            </div>
                        </div>
                    </Form>

                {/* Action Buttons */}
                <div className="flex items-center justify-end gap-3 rounded-lg border-t bg-white p-6 shadow-sm">
                    <Button
                        variant="secondary"
                        size="lg"
                        className="border border-gray-300 bg-white px-6 font-semibold text-gray-700 shadow-sm hover:bg-gray-100"
                        onClick={() => router.visit(route('admin.tenants.index'))}
                    >
                        Cancel
                    </Button>
                    <Button
                        type="submit"
                        form="tenant-form"
                        variant="default"
                        size="lg"
                        className="flex items-center gap-2 bg-blue-600 px-8 font-bold text-white shadow-md hover:bg-blue-700"
                    >
                        <Save className="mr-2 h-5 w-5" />
                        {isEdit ? 'Save Changes' : 'Create Tenant'}
                    </Button>
                </div>
            </div>
        </>
    );
}
