'use client';

import { useState, useEffect } from 'react';
import Layout from '@/components/Layout';

interface Vendor {
    id: number;
    vendor_name: string;
    main_contact_person?: string;
    main_contact_number?: string;
    office_number?: string;
    email?: string;
    address?: string;
    service_type?: string;
    service_types?: string[];
    notes?: string; // Assignment Notes (per-property notes from pivot table)
}

interface Property {
    id: number;
    property_name: string;
    property_number?: string;
    address: string;
    city: string;
    state: string;
    zip_code?: string;
    units?: number;
    phone?: string;
    status: string;
    user_role?: 'manager' | 'service_manager';
    manager?: {
        id: number;
        name: string;
        email: string;
    };
    service_manager?: {
        id: number;
        name: string;
        email: string;
    };
    vendors: Vendor[];
}

interface DashboardData {
    properties: Property[];
    user: {
        name: string;
        email: string;
        role: string;
    };
}

const getVendorServices = (vendor: Vendor): string[] => {
    // #region agent log
    fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:43',message:'getVendorServices called',data:{vendorId:vendor.id,hasServiceTypes:!!vendor.service_types,serviceTypesType:typeof vendor.service_types,serviceTypesIsArray:Array.isArray(vendor.service_types),serviceTypesLength:Array.isArray(vendor.service_types)?vendor.service_types.length:0,hasServiceType:!!vendor.service_type},sessionId:'debug-session',runId:'run1',hypothesisId:'H6'})}).catch(()=>{});
    // #endregion
    
    // Handle service_types array - should always be an array from the API
    // Check if service_types exists and is a valid array (even if empty)
    if (vendor.service_types !== null && vendor.service_types !== undefined) {
        if (Array.isArray(vendor.service_types)) {
            // If it's an array with items, return it
            if (vendor.service_types.length > 0) {
                // #region agent log
                fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:49',message:'Using service_types array',data:{vendorId:vendor.id,serviceTypesCount:vendor.service_types.length,serviceTypes:vendor.service_types},sessionId:'debug-session',runId:'run1',hypothesisId:'H6'})}).catch(()=>{});
                // #endregion
                return vendor.service_types;
            }
            // If it's an empty array, fall through to check service_type
        } else if (typeof vendor.service_types === 'string') {
            // Handle case where API might return a string instead of array
            // #region agent log
            fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:56',message:'service_types is string, converting to array',data:{vendorId:vendor.id,serviceTypesString:vendor.service_types},sessionId:'debug-session',runId:'run1',hypothesisId:'H6'})}).catch(()=>{});
            // #endregion
            // Parse comma-separated string
            const serviceTypesStr = vendor.service_types as string;
            const parsed = serviceTypesStr.split(',').map((s: string) => s.trim()).filter(Boolean);
            if (parsed.length > 0) {
                return parsed;
            }
        }
    }

    // Fallback to single service_type for backward compatibility
    // #region agent log
    fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:65',message:'Falling back to service_type',data:{vendorId:vendor.id,serviceType:vendor.service_type},sessionId:'debug-session',runId:'run1',hypothesisId:'H7'})}).catch(()=>{});
    // #endregion
    return vendor.service_type ? [vendor.service_type] : [];
};

const applyVendorFilter = (vendors: Vendor[] = [], query: string, serviceTypeFilter?: string): Vendor[] => {
    let filtered = vendors;

    // Apply text search filter
    const normalized = query.toLowerCase().trim();
    if (normalized) {
        filtered = filtered.filter((vendor) => {
            const fields = [
                vendor.vendor_name,
                vendor.main_contact_person,
                vendor.main_contact_number,
                vendor.office_number,
                vendor.email,
                vendor.address,
            ].filter(Boolean) as string[];

            const services = getVendorServices(vendor);

            return (
                fields.some((field) => field.toLowerCase().includes(normalized)) ||
                services.some((service) => service.toLowerCase().includes(normalized))
            );
        });
    }

    // Apply service type filter
    if (serviceTypeFilter) {
        filtered = filtered.filter((vendor) => {
            const services = getVendorServices(vendor);
            return services.some((service) => service.toLowerCase() === serviceTypeFilter.toLowerCase());
        });
    }

    return filtered;
};

export default function DashboardPage() {
    const [data, setData] = useState<DashboardData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [vendorFilters, setVendorFilters] = useState<Record<number, string>>({});
    const [vendorServiceTypeFilters, setVendorServiceTypeFilters] = useState<Record<number, string>>({});
    const [vendorViews, setVendorViews] = useState<Record<number, 'grid' | 'list'>>({});

    // Load view preferences from localStorage on mount
    useEffect(() => {
        const savedViews = localStorage.getItem('vendorViewPreferences');
        if (savedViews) {
            try {
                const parsed = JSON.parse(savedViews);
                setVendorViews(parsed);
            } catch (e) {
                console.error('Failed to parse saved view preferences:', e);
            }
        }
    }, []);

    useEffect(() => {
        fetchDashboardData();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // Auto-refresh vendor data every 30 seconds to sync service types updates from admin
    useEffect(() => {
        const interval = setInterval(() => {
            if (!loading && data) {
                fetchDashboardData(true); // Silent refresh
            }
        }, 30000); // 30 seconds

        return () => clearInterval(interval);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [loading, data]);

    const fetchDashboardData = async (silent = false) => {
        try {
            const response = await fetch('/api/dashboard', {
                method: 'GET',
                credentials: 'include',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
            });

            if (!response.ok) {
                if (response.status === 401) {
                    window.location.href = '/login';
                    return;
                }
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.error || `Failed to fetch dashboard data: ${response.status}`);
            }

            const result = await response.json();
            // Debug: Log vendor service types
            console.log('🔍 Full API Response:', JSON.stringify(result, null, 2));
            // #region agent log
            fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:121',message:'Dashboard data received',data:{hasProperties:!!result.properties,propertiesCount:result.properties?.length||0},sessionId:'debug-session',runId:'run1',hypothesisId:'H9'})}).catch(()=>{});
            // #endregion
            if (result.properties && result.properties.length > 0) {
                result.properties.forEach((property: Property) => {
                    console.log(`📦 Property: ${property.property_name}, Vendors: ${property.vendors?.length || 0}`);
                    console.log(`👔 Manager:`, property.manager, 'hasManager:', !!property.manager);
                    console.log(`🔧 Service Manager:`, property.service_manager, 'hasServiceManager:', !!property.service_manager);
                    if (property.vendors && property.vendors.length > 0) {
                        property.vendors.forEach((vendor: Vendor) => {
                            // #region agent log
                            fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:128',message:'Vendor service types from API',data:{vendorId:vendor.id,vendorName:vendor.vendor_name,serviceTypes:vendor.service_types,serviceTypesType:typeof vendor.service_types,serviceTypesIsArray:Array.isArray(vendor.service_types),serviceTypesLength:Array.isArray(vendor.service_types)?vendor.service_types.length:0,serviceType:vendor.service_type},sessionId:'debug-session',runId:'run1',hypothesisId:'H6'})}).catch(()=>{});
                            // #endregion
                            const servicesFromFunction = getVendorServices(vendor);
                            console.log(`👤 Vendor: ${vendor.vendor_name}`, {
                                service_types: vendor.service_types,
                                service_types_type: typeof vendor.service_types,
                                service_types_isArray: Array.isArray(vendor.service_types),
                                service_types_length: Array.isArray(vendor.service_types) ? vendor.service_types.length : 0,
                                service_type: vendor.service_type,
                                servicesFromFunction: servicesFromFunction,
                                servicesFromFunctionLength: servicesFromFunction.length,
                                notes: vendor.notes,
                            });
                        });
                    }
                });
            }
            setData(result);
            // #region agent log
            fetch('http://127.0.0.1:7243/ingest/32873bf1-8708-4426-8b67-6fb5a9a24211',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'dashboard/page.tsx:141',message:'Dashboard state updated',data:{timestamp:Date.now()},sessionId:'debug-session',runId:'run1',hypothesisId:'H8'})}).catch(()=>{});
            // #endregion
            
            // Only show error if not a silent refresh
            if (!silent && error) {
                setError(null);
            }
        } catch (err) {
            console.error('Dashboard fetch error:', err);
            // Only set error if not a silent refresh
            if (!silent) {
                setError(err instanceof Error ? err.message : 'An error occurred. Check console for details.');
            }
        } finally {
            if (!silent) {
                setLoading(false);
            }
        }
    };

    const handleVendorFilterChange = (propertyId: number, value: string) => {
        setVendorFilters((prev) => ({
            ...prev,
            [propertyId]: value,
        }));
    };

    const handleVendorViewChange = (propertyId: number, view: 'grid' | 'list') => {
        const newViews = {
            ...vendorViews,
            [propertyId]: view,
        };
        setVendorViews(newViews);
        // Persist to localStorage
        try {
            localStorage.setItem('vendorViewPreferences', JSON.stringify(newViews));
        } catch (e) {
            console.error('Failed to save view preferences:', e);
        }
    };

    const handleClearFilter = (propertyId: number) => {
        setVendorFilters((prev) => {
            const updated = { ...prev };
            delete updated[propertyId];
            return updated;
        });
        setVendorServiceTypeFilters((prev) => {
            const updated = { ...prev };
            delete updated[propertyId];
            return updated;
        });
    };

    const handleServiceTypeFilterChange = (propertyId: number, value: string) => {
        setVendorServiceTypeFilters((prev) => ({
            ...prev,
            [propertyId]: value,
        }));
    };

    const getAllServiceTypes = (vendors: Vendor[]): string[] => {
        const serviceTypesSet = new Set<string>();
        vendors.forEach((vendor) => {
            const services = getVendorServices(vendor);
            services.forEach((service) => serviceTypesSet.add(service));
        });
        return Array.from(serviceTypesSet).sort();
    };

    const formatPhoneNumber = (phone: string) => {
        if (!phone) return '';
        // Remove all non-numeric characters except +
        const cleaned = phone.replace(/[^\d+]/g, '');
        // Format as (XXX) XXX-XXXX if it's a 10-digit number
        if (cleaned.length === 10) {
            return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6)}`;
        }
        return phone;
    };

    if (loading) {
        return (
            <Layout>
                <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-zinc-50 to-zinc-100 dark:from-zinc-900 dark:to-zinc-800">
                    <div className="text-center">
                        <div className="inline-block h-12 w-12 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent"></div>
                        <p className="mt-4 text-lg font-medium text-zinc-700 dark:text-zinc-300">Loading your properties...</p>
                    </div>
                </div>
            </Layout>
        );
    }

    if (error) {
        return (
            <Layout>
                <div className="min-h-screen bg-gradient-to-br from-zinc-50 to-zinc-100 dark:from-zinc-900 dark:to-zinc-800">
                    <div className="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8">
                        <div className="rounded-lg bg-red-50 border border-red-200 p-6 dark:bg-red-900/20 dark:border-red-800">
                            <div className="flex">
                                <div className="flex-shrink-0">
                                    <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                    </svg>
                                </div>
                                <div className="ml-3 flex-1">
                                    <h3 className="text-sm font-medium text-red-800 dark:text-red-200">Error loading dashboard</h3>
                                    <p className="mt-2 text-sm text-red-700 dark:text-red-300">{error}</p>
                                    <div className="mt-4">
                                        <button
                                            onClick={() => fetchDashboardData(false)}
                                            className="rounded-md bg-red-100 px-3 py-2 text-sm font-medium text-red-800 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-200 dark:hover:bg-red-900/50"
                                        >
                                            Try Again
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </Layout>
        );
    }

    if (!data) {
        return null;
    }

    const { properties, user } = data;

    return (
        <Layout>
            <div className="min-h-screen bg-gradient-to-br from-zinc-50 via-white to-zinc-50 dark:from-zinc-900 dark:via-zinc-800 dark:to-zinc-900">
                <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
                    {/* Header Section */}
                    <div className="mb-8">
                        <div className="flex items-center justify-between">
                            <div>
                                <h1 className="text-3xl font-bold text-zinc-900 dark:text-white sm:text-4xl">
                                    Welcome, {user.name.split(' ')[0]}
                                </h1>
                                <p className="mt-2 text-lg text-zinc-600 dark:text-zinc-400">
                                    Your assigned properties and vendor contacts
                                </p>
                            </div>
                            <div className="hidden sm:block">
                                <div className="rounded-lg bg-white px-4 py-2 shadow-sm border border-zinc-200 dark:bg-zinc-800 dark:border-zinc-700">
                                    <p className="text-xs text-zinc-500 dark:text-zinc-400">Total Properties</p>
                                    <p className="text-2xl font-bold text-zinc-900 dark:text-white">{properties.length}</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Properties List */}
                    {properties && properties.length > 0 ? (
                        <div className="space-y-6">
                            {properties.map((property) => {
                                const filterQuery = vendorFilters[property.id] ?? '';
                                const serviceTypeFilter = vendorServiceTypeFilters[property.id] ?? '';
                                const viewMode = vendorViews[property.id] ?? 'grid';
                                const filteredVendors = applyVendorFilter(property.vendors, filterQuery, serviceTypeFilter);
                                const vendorCount = property.vendors?.length ?? 0;
                                const hasVendors = vendorCount > 0;
                                const hasMatches = filteredVendors.length > 0;
                                const allServiceTypes = getAllServiceTypes(property.vendors || []);
                                const hasActiveFilters = filterQuery || serviceTypeFilter;

                                return (
                                    <div
                                        key={property.id}
                                        className="overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-lg transition-shadow hover:shadow-xl dark:border-zinc-700 dark:bg-zinc-800"
                                    >
                                    {/* Property Header */}
                                    <div className="bg-gradient-to-r from-blue-600 via-blue-700 to-indigo-700 px-6 py-6 sm:px-8">
                                        <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
                                            <div className="flex-1">
                                                <div className="flex items-center gap-3 flex-wrap">
                                                    <h2 className="text-2xl font-bold text-white sm:text-3xl">
                                                        {property.property_name}
                                                    </h2>
                                                    {property.user_role && (
                                                        <span className="inline-flex items-center rounded-full bg-white/20 px-3 py-1 text-xs font-semibold text-white backdrop-blur-sm">
                                                            {property.user_role === 'manager' ? 'Manager' : 'Service Manager'}
                                                        </span>
                                                    )}
                                                </div>
                                                {property.property_number && (
                                                    <p className="mt-2 text-sm text-blue-100">Property #{property.property_number}</p>
                                                )}
                                            </div>
                                            <div className="flex items-center gap-3">
                                                <span
                                                    className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${
                                                        property.status === 'active'
                                                            ? 'bg-green-500/20 text-green-100 backdrop-blur-sm'
                                                            : 'bg-red-500/20 text-red-100 backdrop-blur-sm'
                                                    }`}
                                                >
                                                    {property.status === 'active' ? 'Active' : 'Inactive'}
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Property Details */}
                                    <div className="p-6 sm:p-8">
                                        {/* Management Team Section */}
                                        {(property.manager || property.service_manager) && (
                                            <div className="mb-8 rounded-lg border border-zinc-200 bg-gradient-to-br from-zinc-50 to-white p-6 dark:border-zinc-700 dark:from-zinc-900/50 dark:to-zinc-800/50">
                                                <h3 className="mb-4 text-lg font-bold text-zinc-900 dark:text-white">
                                                    Management Team
                                                </h3>
                                                <div className="grid gap-6 sm:grid-cols-2">
                                                    {/* Manager */}
                                                    <div className="flex gap-4">
                                                        <div className="flex-shrink-0">
                                                            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/30">
                                                                <svg className="h-6 w-6 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                                </svg>
                                                            </div>
                                                        </div>
                                                        <div className="flex-1">
                                                            <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:text-zinc-400">Property Manager</p>
                                                            {property.manager ? (
                                                                <>
                                                                    <p className="mt-1 text-base font-bold text-zinc-900 dark:text-white">
                                                                        {property.manager.name}
                                                                    </p>
                                                                    {property.manager.email && (
                                                                        <a
                                                                            href={`mailto:${property.manager.email}`}
                                                                            className="mt-1 block text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                                        >
                                                                            {property.manager.email}
                                                                        </a>
                                                                    )}
                                                                </>
                                                            ) : (
                                                                <p className="mt-1 text-sm text-zinc-400 dark:text-zinc-500">Not assigned</p>
                                                            )}
                                                        </div>
                                                    </div>

                                                    {/* Service Manager */}
                                                    <div className="flex gap-4">
                                                        <div className="flex-shrink-0">
                                                            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-indigo-100 dark:bg-indigo-900/30">
                                                                <svg className="h-6 w-6 text-indigo-600 dark:text-indigo-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                                </svg>
                                                            </div>
                                                        </div>
                                                        <div className="flex-1">
                                                            <p className="text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:text-zinc-400">Service Manager</p>
                                                            {property.service_manager ? (
                                                                <>
                                                                    <p className="mt-1 text-base font-bold text-zinc-900 dark:text-white">
                                                                        {property.service_manager.name}
                                                                    </p>
                                                                    {property.service_manager.email && (
                                                                        <a
                                                                            href={`mailto:${property.service_manager.email}`}
                                                                            className="mt-1 block text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                                        >
                                                                            {property.service_manager.email}
                                                                        </a>
                                                                    )}
                                                                </>
                                                            ) : (
                                                                <p className="mt-1 text-sm text-zinc-400 dark:text-zinc-500">Not assigned</p>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        )}

                                        {/* Property Information Grid */}
                                        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 mb-8">
                                            {/* Address */}
                                            <div className="flex gap-3">
                                                <div className="flex-shrink-0">
                                                    <svg className="h-6 w-6 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    </svg>
                                                </div>
                                                <div>
                                                    <p className="text-sm font-medium text-zinc-500 dark:text-zinc-400">Address</p>
                                                    <p className="mt-1 text-base font-semibold text-zinc-900 dark:text-white">
                                                        {property.address}
                                                    </p>
                                                    <p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">
                                                        {property.city}, {property.state} {property.zip_code}
                                                    </p>
                                                </div>
                                            </div>

                                            {/* Manager Name */}
                                            <div className="flex gap-3">
                                                <div className="flex-shrink-0">
                                                    <svg className="h-6 w-6 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                    </svg>
                                                </div>
                                                <div>
                                                    <p className="text-sm font-medium text-zinc-500 dark:text-zinc-400">Manager</p>
                                                    <p className="mt-1 text-base font-semibold text-zinc-900 dark:text-white">
                                                        {property.manager?.name || 'Not assigned'}
                                                    </p>
                                                </div>
                                            </div>

                                            {/* Service Manager Name */}
                                            <div className="flex gap-3">
                                                <div className="flex-shrink-0">
                                                    <svg className="h-6 w-6 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                    </svg>
                                                </div>
                                                <div>
                                                    <p className="text-sm font-medium text-zinc-500 dark:text-zinc-400">Service Manager</p>
                                                    <p className="mt-1 text-base font-semibold text-zinc-900 dark:text-white">
                                                        {property.service_manager?.name || 'Not assigned'}
                                                    </p>
                                                </div>
                                            </div>

                                            {/* Telephone */}
                                            <div className="flex gap-3">
                                                <div className="flex-shrink-0">
                                                    <svg className="h-6 w-6 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                    </svg>
                                                </div>
                                                <div>
                                                    <p className="text-sm font-medium text-zinc-500 dark:text-zinc-400">Telephone</p>
                                                    {property.phone ? (
                                                        <a
                                                            href={`tel:${property.phone.replace(/[^0-9+]/g, '')}`}
                                                            className="mt-1 text-base font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                        >
                                                            {formatPhoneNumber(property.phone)}
                                                        </a>
                                                    ) : (
                                                        <p className="mt-1 text-base font-semibold text-zinc-400 dark:text-zinc-500">Not provided</p>
                                                    )}
                                                </div>
                                            </div>

                                            {/* Units */}
                                            {property.units && (
                                                <div className="flex gap-3">
                                                    <div className="flex-shrink-0">
                                                        <svg className="h-6 w-6 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <p className="text-sm font-medium text-zinc-500 dark:text-zinc-400">Units</p>
                                                        <p className="mt-1 text-base font-semibold text-zinc-900 dark:text-white">
                                                            {property.units} {property.units === 1 ? 'unit' : 'units'}
                                                        </p>
                                                    </div>
                                                </div>
                                            )}
                                        </div>

                                        {/* Vendors Section */}
                                        <div className="border-t border-zinc-200 pt-6 dark:border-zinc-700">
                                            {/* Header Row */}
                                            <div className="mb-4 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                                                <div className="flex-1">
                                                    <h3 className="text-lg font-bold text-zinc-900 dark:text-white">
                                                        Vendor Contacts
                                                        <span className="ml-2 text-base font-normal text-zinc-500 dark:text-zinc-400">
                                                            ({vendorCount})
                                                        </span>
                                                    </h3>
                                                </div>
                                                <div className="flex-shrink-0">
                                                    <div className="inline-flex rounded-lg border border-zinc-200 bg-white p-1 text-xs font-semibold text-zinc-500 dark:border-zinc-700 dark:bg-zinc-900">
                                                        {(['grid', 'list'] as const).map((view) => {
                                                            const isActive = viewMode === view;
                                                            return (
                                                                <button
                                                                    key={view}
                                                                    type="button"
                                                                    onClick={() => handleVendorViewChange(property.id, view)}
                                                                    className={`inline-flex items-center gap-1.5 rounded-md px-3 py-2 text-xs font-semibold transition-all duration-200 ${
                                                                        isActive
                                                                            ? 'bg-blue-600 text-white shadow-sm scale-105'
                                                                            : 'text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-100'
                                                                    }`}
                                                                >
                                                                    {view === 'grid' ? (
                                                                        <>
                                                                            <svg
                                                                                className="h-4 w-4"
                                                                                xmlns="http://www.w3.org/2000/svg"
                                                                                fill="none"
                                                                                viewBox="0 0 24 24"
                                                                                strokeWidth={1.5}
                                                                                stroke="currentColor"
                                                                            >
                                                                                <path
                                                                                    strokeLinecap="round"
                                                                                    strokeLinejoin="round"
                                                                                    d="M3.75 5.25h4.5v4.5h-4.5v-4.5zM15.75 5.25h4.5v4.5h-4.5v-4.5zM15.75 15.75h4.5v4.5h-4.5v-4.5zM3.75 15.75h4.5v4.5h-4.5v-4.5z"
                                                                                />
                                                                            </svg>
                                                                            <span>Grid</span>
                                                                        </>
                                                                    ) : (
                                                                        <>
                                                                            <svg
                                                                                className="h-4 w-4"
                                                                                xmlns="http://www.w3.org/2000/svg"
                                                                                fill="none"
                                                                                viewBox="0 0 24 24"
                                                                                strokeWidth={1.5}
                                                                                stroke="currentColor"
                                                                            >
                                                                                <path
                                                                                    strokeLinecap="round"
                                                                                    strokeLinejoin="round"
                                                                                    d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5"
                                                                                />
                                                                            </svg>
                                                                            <span>List</span>
                                                                        </>
                                                                    )}
                                                                </button>
                                                            );
                                                        })}
                                                    </div>
                                                </div>
                                            </div>

                                            {/* Filter Section */}
                                            {hasVendors && (
                                                <div className="mb-6 rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-900/50">
                                                    <div className="mb-4 flex items-center justify-between">
                                                        <label className="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">
                                                            Filter vendors
                                                            {hasActiveFilters && (
                                                                <span className="ml-2 inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-200">
                                                                    {filteredVendors.length} of {vendorCount}
                                                                </span>
                                                            )}
                                                        </label>
                                                        {hasActiveFilters && (
                                                            <button
                                                                type="button"
                                                                onClick={() => handleClearFilter(property.id)}
                                                                className="text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                            >
                                                                Clear all
                                                            </button>
                                                        )}
                                                    </div>
                                                    <div className="grid gap-4 sm:grid-cols-2">
                                                        {/* Text Search */}
                                                        <div className="relative">
                                                            <label
                                                                htmlFor={`vendor-filter-${property.id}`}
                                                                className="mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400"
                                                            >
                                                                Search vendors
                                                            </label>
                                                            <input
                                                                id={`vendor-filter-${property.id}`}
                                                                type="text"
                                                                value={filterQuery}
                                                                onChange={(event) =>
                                                                    handleVendorFilterChange(property.id, event.target.value)
                                                                }
                                                                placeholder="Search by vendor, contact, service, phone, or email"
                                                                className="w-full rounded-lg border border-zinc-200 bg-white px-4 py-2.5 pr-10 text-sm text-zinc-700 placeholder:text-zinc-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/30 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 transition-all duration-200"
                                                            />
                                                            {filterQuery ? (
                                                                <button
                                                                    type="button"
                                                                    onClick={() => {
                                                                        setVendorFilters((prev) => {
                                                                            const updated = { ...prev };
                                                                            delete updated[property.id];
                                                                            return updated;
                                                                        });
                                                                    }}
                                                                    className="absolute right-3 top-1/2 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"
                                                                >
                                                                    <svg
                                                                        className="h-4 w-4"
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        fill="none"
                                                                        viewBox="0 0 24 24"
                                                                        strokeWidth={2}
                                                                        stroke="currentColor"
                                                                    >
                                                                        <path
                                                                            strokeLinecap="round"
                                                                            strokeLinejoin="round"
                                                                            d="M6 18L18 6M6 6l12 12"
                                                                        />
                                                                    </svg>
                                                                </button>
                                                            ) : (
                                                                <svg
                                                                    className="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400"
                                                                    xmlns="http://www.w3.org/2000/svg"
                                                                    fill="none"
                                                                    viewBox="0 0 24 24"
                                                                    strokeWidth={1.5}
                                                                    stroke="currentColor"
                                                                >
                                                                    <path
                                                                        strokeLinecap="round"
                                                                        strokeLinejoin="round"
                                                                        d="M21 21l-3.5-3.5M19 11a8 8 0 11-16 0 8 8 0 0116 0z"
                                                                    />
                                                                </svg>
                                                            )}
                                                        </div>
                                                        {/* Service Type Filter */}
                                                        <div className="relative">
                                                            <label
                                                                htmlFor={`service-type-filter-${property.id}`}
                                                                className="mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400"
                                                            >
                                                                Filter by service type
                                                            </label>
                                                            <select
                                                                id={`service-type-filter-${property.id}`}
                                                                value={serviceTypeFilter}
                                                                onChange={(event) =>
                                                                    handleServiceTypeFilterChange(property.id, event.target.value)
                                                                }
                                                                className="w-full rounded-lg border border-zinc-200 bg-white px-4 py-2.5 pr-10 text-sm text-zinc-700 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/30 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 transition-all duration-200 appearance-none cursor-pointer"
                                                            >
                                                                <option value="">All service types</option>
                                                                {allServiceTypes.length > 0 ? (
                                                                    allServiceTypes.map((serviceType) => (
                                                                        <option key={serviceType} value={serviceType}>
                                                                            {serviceType}
                                                                        </option>
                                                                    ))
                                                                ) : (
                                                                    <option value="" disabled>
                                                                        No service types available
                                                                    </option>
                                                                )}
                                                            </select>
                                                            <svg
                                                                className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400"
                                                                xmlns="http://www.w3.org/2000/svg"
                                                                fill="none"
                                                                viewBox="0 0 24 24"
                                                                strokeWidth={2}
                                                                stroke="currentColor"
                                                            >
                                                                <path
                                                                    strokeLinecap="round"
                                                                    strokeLinejoin="round"
                                                                    d="M19.5 8.25l-7.5 7.5-7.5-7.5"
                                                                />
                                                            </svg>
                                                        </div>
                                                    </div>
                                                </div>
                                            )}

                                            {hasVendors ? (
                                                hasMatches ? (
                                                    viewMode === 'list' ? (
                                                        <div className="overflow-x-auto rounded-xl border border-zinc-200 dark:border-zinc-700 transition-opacity duration-300">
                                                            <table className="min-w-full divide-y divide-zinc-200 text-sm dark:divide-zinc-700">
                                                                <thead className="bg-zinc-50 text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:bg-zinc-900 dark:text-zinc-400">
                                                                    <tr>
                                                                        <th className="px-4 py-3 text-left">Vendor</th>
                                                                        <th className="px-4 py-3 text-left">Services</th>
                                                                        <th className="px-4 py-3 text-left">Contact</th>
                                                                        <th className="px-4 py-3 text-left">Phone</th>
                                                                        <th className="px-4 py-3 text-left">Email</th>
                                                                        <th className="px-4 py-3 text-left">Actions</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody className="divide-y divide-zinc-100 text-zinc-700 dark:divide-zinc-800 dark:text-zinc-200">
                                                                    {filteredVendors.map((vendor) => (
                                                                        <tr key={vendor.id} className="bg-white dark:bg-zinc-900/40">
                                                                            <td className="px-4 py-4">
                                                                                <p className="font-semibold text-zinc-900 dark:text-white">
                                                                                    {vendor.vendor_name}
                                                                                </p>
                                                                                {vendor.notes && (
                                                                                    <div className="mt-1">
                                                                                        <p className="text-xs font-medium text-amber-700 dark:text-amber-300 mb-0.5">Assignment Notes:</p>
                                                                                        <p className="text-xs text-amber-600 dark:text-amber-300">
                                                                                            {vendor.notes}
                                                                                        </p>
                                                                                    </div>
                                                                                )}
                                                                            </td>
                                                                            <td className="px-4 py-4">
                                                                                <div className="flex flex-wrap gap-1">
                                                                                    {(() => {
                                                                                        const services = getVendorServices(vendor);
                                                                                        console.log(`[DEBUG] Vendor ${vendor.id} (${vendor.vendor_name}) services:`, services);
                                                                                        return services.map((service) => (
                                                                                            <span
                                                                                                key={`${vendor.id}-${service}`}
                                                                                                className="inline-flex items-center rounded-full bg-blue-50 px-2 py-0.5 text-[11px] font-semibold text-blue-700 dark:bg-blue-500/10 dark:text-blue-200"
                                                                                            >
                                                                                                {service}
                                                                                            </span>
                                                                                        ));
                                                                                    })()}
                                                                                </div>
                                                                            </td>
                                                                            <td className="px-4 py-4">
                                                                                <div className="space-y-1 text-xs">
                                                                                    {vendor.main_contact_person && (
                                                                                        <p className="font-medium text-zinc-900 dark:text-white">
                                                                                            {vendor.main_contact_person}
                                                                                        </p>
                                                                                    )}
                                                                                    {vendor.address && (
                                                                                        <p className="text-zinc-500 dark:text-zinc-400">{vendor.address}</p>
                                                                                    )}
                                                                                </div>
                                                                            </td>
                                                                            <td className="px-4 py-4">
                                                                                <div className="space-y-1 text-xs">
                                                                                    {vendor.main_contact_number && (
                                                                                        <a
                                                                                            href={`tel:${vendor.main_contact_number.replace(/[^0-9+]/g, '')}`}
                                                                                            className="font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                                                        >
                                                                                            {formatPhoneNumber(vendor.main_contact_number)}
                                                                                        </a>
                                                                                    )}
                                                                                    {vendor.office_number && (
                                                                                        <a
                                                                                            href={`tel:${vendor.office_number.replace(/[^0-9+]/g, '')}`}
                                                                                            className="text-xs text-zinc-500 hover:text-blue-600 dark:text-zinc-400 dark:hover:text-blue-400"
                                                                                        >
                                                                                            Office: {formatPhoneNumber(vendor.office_number)}
                                                                                        </a>
                                                                                    )}
                                                                                </div>
                                                                            </td>
                                                                            <td className="px-4 py-4">
                                                                                {vendor.email ? (
                                                                                    <a
                                                                                        href={`mailto:${vendor.email}`}
                                                                                        className="text-sm font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                                                    >
                                                                                        {vendor.email}
                                                                                    </a>
                                                                                ) : (
                                                                                    <span className="text-xs text-zinc-400">—</span>
                                                                                )}
                                                                            </td>
                                                                            <td className="px-4 py-4">
                                                                                <div className="flex gap-2">
                                                                                    {vendor.main_contact_number && (
                                                                                        <a
                                                                                            href={`tel:${vendor.main_contact_number.replace(/[^0-9+]/g, '')}`}
                                                                                            className="inline-flex items-center rounded-md border border-zinc-200 px-2 py-1 text-xs font-semibold text-zinc-600 transition-colors hover:border-blue-500 hover:text-blue-600 dark:border-zinc-700 dark:text-zinc-300 dark:hover:border-blue-400 dark:hover:text-blue-300"
                                                                                        >
                                                                                            Call
                                                                                        </a>
                                                                                    )}
                                                                                    {vendor.email && (
                                                                                        <a
                                                                                            href={`mailto:${vendor.email}`}
                                                                                            className="inline-flex items-center rounded-md border border-zinc-200 px-2 py-1 text-xs font-semibold text-zinc-600 transition-colors hover:border-blue-500 hover:text-blue-600 dark:border-zinc-700 dark:text-zinc-300 dark:hover:border-blue-400 dark:hover:text-blue-300"
                                                                                        >
                                                                                            Email
                                                                                        </a>
                                                                                    )}
                                                                                </div>
                                                                            </td>
                                                                        </tr>
                                                                    ))}
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    ) : (
                                                        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 transition-opacity duration-300">
                                                            {filteredVendors.map((vendor) => {
                                                                const services = getVendorServices(vendor);
                                                                console.log(`[DEBUG] Grid Vendor ${vendor.id} (${vendor.vendor_name}) services:`, services, 'service_types:', vendor.service_types, 'service_type:', vendor.service_type);

                                                                return (
                                                                    <div
                                                                        key={vendor.id}
                                                                        className="group relative rounded-lg border border-zinc-200 bg-zinc-50 p-5 transition-all duration-200 hover:border-blue-300 hover:shadow-md dark:border-zinc-700 dark:bg-zinc-900/50 dark:hover:border-blue-600"
                                                                    >
                                                                        <div className="mb-4">
                                                                            <h4 className="text-lg font-bold text-zinc-900 dark:text-white mb-2">
                                                                                {vendor.vendor_name}
                                                                            </h4>
                                                                            <div className="flex flex-wrap gap-2">
                                                                                {services.map((serviceType) => (
                                                                                    <span
                                                                                        key={`${vendor.id}-${serviceType}`}
                                                                                        className="inline-flex items-center rounded-md bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-300"
                                                                                    >
                                                                                        {serviceType}
                                                                                    </span>
                                                                                ))}
                                                                            </div>
                                                                        </div>

                                                                        <div className="space-y-3">
                                                                            {vendor.main_contact_person && (
                                                                                <div className="flex items-start gap-2 text-sm">
                                                                                    <svg className="h-5 w-5 mt-0.5 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                                                    </svg>
                                                                                    <span className="text-zinc-700 dark:text-zinc-300">{vendor.main_contact_person}</span>
                                                                                </div>
                                                                            )}

                                                                            {vendor.main_contact_number && (
                                                                                <div className="flex items-start gap-2 text-sm">
                                                                                    <svg className="h-5 w-5 mt-0.5 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                                                    </svg>
                                                                                    <a
                                                                                        href={`tel:${vendor.main_contact_number.replace(/[^0-9+]/g, '')}`}
                                                                                        className="font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                                                    >
                                                                                        {formatPhoneNumber(vendor.main_contact_number)}
                                                                                    </a>
                                                                                </div>
                                                                            )}

                                                                            {vendor.office_number && (
                                                                                <div className="flex items-start gap-2 text-sm">
                                                                                    <svg className="h-5 w-5 mt-0.5 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                                                    </svg>
                                                                                    <div>
                                                                                        <span className="text-zinc-600 dark:text-zinc-400">Office: </span>
                                                                                        <a
                                                                                            href={`tel:${vendor.office_number.replace(/[^0-9+]/g, '')}`}
                                                                                            className="font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                                                                                        >
                                                                                            {formatPhoneNumber(vendor.office_number)}
                                                                                        </a>
                                                                                    </div>
                                                                                </div>
                                                                            )}

                                                                            {vendor.email && (
                                                                                <div className="flex items-start gap-2 text-sm">
                                                                                    <svg className="h-5 w-5 mt-0.5 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                                                    </svg>
                                                                                    <a
                                                                                        href={`mailto:${vendor.email}`}
                                                                                        className="font-semibold text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 break-all"
                                                                                    >
                                                                                        {vendor.email}
                                                                                    </a>
                                                                                </div>
                                                                            )}

                                                                            {vendor.address && (
                                                                                <div className="flex items-start gap-2 text-sm">
                                                                                    <svg className="h-5 w-5 mt-0.5 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                                                                    </svg>
                                                                                    <span className="text-zinc-700 dark:text-zinc-300">{vendor.address}</span>
                                                                                </div>
                                                                            )}

                                                                            {vendor.notes && (
                                                                                <div className="mt-3 rounded-md bg-amber-50 border border-amber-200 p-3 dark:bg-amber-900/20 dark:border-amber-800">
                                                                                    <p className="text-xs font-medium text-amber-800 dark:text-amber-200 mb-1">Assignment Notes:</p>
                                                                                    <p className="text-xs text-amber-700 dark:text-amber-300">{vendor.notes}</p>
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="mt-4 pt-4 border-t border-zinc-200 dark:border-zinc-700 flex gap-2">
                                                                            {vendor.main_contact_number && (
                                                                                <a
                                                                                    href={`tel:${vendor.main_contact_number.replace(/[^0-9+]/g, '')}`}
                                                                                    className="flex-1 inline-flex items-center justify-center gap-2 rounded-md bg-blue-600 px-3 py-2 text-xs font-semibold text-white transition-colors hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600"
                                                                                >
                                                                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                                                    </svg>
                                                                                    Call
                                                                                </a>
                                                                            )}
                                                                            {vendor.email && (
                                                                                <a
                                                                                    href={`mailto:${vendor.email}`}
                                                                                    className="flex-1 inline-flex items-center justify-center gap-2 rounded-md border border-zinc-300 bg-white px-3 py-2 text-xs font-semibold text-zinc-700 transition-colors hover:bg-zinc-50 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700"
                                                                                >
                                                                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                                                    </svg>
                                                                                    Email
                                                                                </a>
                                                                            )}
                                                                        </div>
                                                                    </div>
                                                                );
                                                            })}
                                                        </div>
                                                    )
                                                ) : (
                                                    <div className="rounded-lg border border-dashed border-zinc-300 bg-zinc-50 p-6 text-center dark:border-zinc-700 dark:bg-zinc-900/40">
                                                        <p className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                                                            No vendors match your filter.
                                                        </p>
                                                        <p className="mt-1 text-xs text-zinc-500 dark:text-zinc-400">
                                                            Try adjusting your search to see more contacts.
                                                        </p>
                                                    </div>
                                                )
                                            ) : (
                                                <div className="rounded-lg border border-zinc-200 bg-zinc-50 p-6 text-center dark:border-zinc-700 dark:bg-zinc-900/50">
                                                    <svg className="mx-auto h-12 w-12 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                                                    </svg>
                                                    <p className="mt-4 text-sm font-medium text-zinc-900 dark:text-white">No vendors assigned</p>
                                                    <p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">No vendors have been assigned to this property yet.</p>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                                );
                            })}
                        </div>
                    ) : (
                        <div className="rounded-xl border border-zinc-200 bg-white p-12 text-center shadow-sm dark:border-zinc-700 dark:bg-zinc-800">
                            <svg className="mx-auto h-16 w-16 text-zinc-400 dark:text-zinc-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                            </svg>
                            <h3 className="mt-4 text-lg font-semibold text-zinc-900 dark:text-white">No Properties Assigned</h3>
                            <p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">
                                You don&apos;t have any properties assigned to you yet. Please contact your administrator to get assigned to properties.
                            </p>
                        </div>
                    )}
                </div>
            </div>
        </Layout>
    );
}
