import { ContactDetails } from '@admin/components/addOns/addon-sidebars/contacts/ContactDetails';
import ContactForm from '@admin/components/addOns/addon-sidebars/contacts/ContactForm';
import { Avatar, AvatarFallback, AvatarImage } from '@admin/components/ui/avatar';
import { Button } from '@admin/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@admin/components/ui/dropdown-menu';
import useAddOn from '@/hooks/use-addons';
import { cn } from '@admin/lib/utils';
import { Link, router } from '@inertiajs/react';
import { ArrowLeft, ExternalLinkIcon, Loader2, Mail, MoreVertical, Pencil, Plus, Search, Star, Trash, X } from 'lucide-react';
import { useCallback, useState } from 'react';
import { toast } from 'sonner';
import { route } from 'ziggy-js';

type ServerErrors = Record<string, string>;

export interface Contact {
    id?: string | number;
    name: string;
    primary_email: string;
    primary_phone?: string;
    location?: string;
    company?: string;
    avatar?: string;
    lastContact?: string;
    favorite?: boolean;
    group?: string;
    status?: number;
}

const groupColors: Record<string, string> = {
    Clients: 'bg-blue-50 text-blue-700 border-blue-200',
    Team: 'bg-green-50 text-green-700 border-green-200',
    Partners: 'bg-purple-50 text-purple-700 border-purple-200',
    Vendors: 'bg-amber-50 text-amber-700 border-amber-200',
    Prospects: 'bg-cyan-50 text-cyan-700 border-cyan-200',
};

// Mock contacts data for the sidebar
const mockContacts: Contact[] = Array.from({ length: 15 }).map((_, i) => ({
    id: String(i + 1),
    name: [
        'Veronica Lueilwitz',
        'Sheryl Bins',
        'Marianne Thompson',
        'Cassandra Goodwin',
        'Samantha Ward',
        'Ruben Sporer',
        'Allison Corkery',
        'Lila Schmeler',
        'Judith Rohan',
        'Kayla Greenfelder',
    ][i % 10],
    primary_email: `user${i + 1}@example.com`,
    primary_phone: ['398-719-0220', '1-445-949-8764', '(788) 569-2095', '(904) 679-9183'][i % 4],
    location: ['New York', 'San Francisco', 'Chicago', 'Boston', 'Seattle'][i % 5],
    company: ['Acme Inc.', 'TechCorp', 'GlobalServices', 'NextLevel', 'InnovateCo'][i % 5],
    lastContact: ['2 days ago', '1 week ago', 'Yesterday', '3 hours ago', '1 month ago'][i % 5],
    favorite: i % 4 === 0,
    group: ['Clients', 'Team', 'Partners', 'Vendors', 'Prospects'][i % 5],
}));

type ActiveTab = 'all' | 'favorites' | 'recent';
type GroupFilter = 'all' | 'clients' | 'team' | 'partners' | 'vendors' | 'prospects';

interface ContactAddOnSidebarProps {
    title?: string;
    onClose?: () => void;
    mode?: 'list' | 'add' | 'edit' | 'details';
    initialContact?: Contact;
    module?: 'crm' | 'inventory' | 'company' | '';
    refreshContacts?: () => void;
    appName?: string;
}

export function ContactAddOnSidebar({
    title = 'Contacts',
    onClose,
    mode = 'list',
    initialContact,
    module = '',
    refreshContacts,
    appName = 'main',
}: ContactAddOnSidebarProps) {
    const { addOnClose } = useAddOn();

    const [searchQuery, setSearchQuery] = useState('');
    const [activeTab, setActiveTab] = useState<ActiveTab>('all');
    const [groupFilter, setGroupFilter] = useState<GroupFilter>('all');

    const [sidebarMode, setSidebarMode] = useState<'list' | 'add' | 'edit' | 'details'>(mode);
    const [contacts, setContacts] = useState<Contact[]>(mockContacts);
    const [activeContact, setActiveContact] = useState<Contact | null>(initialContact ?? null);
    const [isLoadingContact, setIsLoadingContact] = useState(false);
    const [serverErrors, setServerErrors] = useState<ServerErrors>({});

    // Fetch full contact details for editing (includes manager, assigned_users)
    const fetchContactDetails = async (contact: Contact) => {
        if (!contact.id && !contact.uid) return contact;

        setIsLoadingContact(true);
        try {
            const contactId = contact.uid || contact.id;
            const response = await fetch(route('contacts.show', { contact: contactId }), {
                headers: {
                    Accept: 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                },
            });

            if (response.ok) {
                const data = await response.json();
                // The response might be wrapped in a 'contact' property or be the contact directly
                return data.contact || data;
            }
        } catch (error) {
            console.error('Failed to fetch contact details:', error);
        } finally {
            setIsLoadingContact(false);
        }
        return contact;
    };

    // Handler to enter edit mode with full contact data
    const handleEditContact = async (contact: Contact) => {
        const fullContact = await fetchContactDetails(contact);
        setActiveContact(fullContact);
        setSidebarMode('edit');
    };

    const getPostRoute = () => {
        if (!module) return route('contacts.store');
        if (module === 'company') return route('crm.company.store');
        return route(`${module}.customer.store`);
    };

    const getPutRoute = (id: string | number) => {
        if (!module) return route('contacts.update', { contact: id });
        if (module === 'company') return route('crm.company.update', id);
        return route(`${module}.customer.update`, { customer: id });
    };

    const handleContactSubmit = useCallback(
        (payload: any) => {
            // Clear previous errors
            setServerErrors({});

            if (sidebarMode === 'add') {
                // Core required fields
                const newContact = {
                    name: payload.name || 'Unnamed',
                    primary_email: payload.primary_email || '',
                    primary_phone: payload.primary_phone || '',
                    is_login: payload.is_login || false,
                    password: payload.is_login ? payload.password || '' : '',
                    app_name: payload.app_name || 'main',
                    source: payload.source || 'lead',
                    assigned_to: payload.assigned_to || [],
                    contact_owner: payload.contact_owner ?? null,
                    type: payload.type ?? 1,
                    category: payload.category ?? 2, // 2 = Customer
                    status: payload.status ?? 1, // Use ?? to allow 0 (inactive) status
                };
                // @ts-ignore
                router.post(getPostRoute(), newContact, {
                    onSuccess: () => {
                        // Notify global listeners to refresh
                        try {
                            refreshContacts?.();
                        } catch {}
                        addOnClose();
                    },
                    onError: (errors: Record<string, string>) => {
                        setServerErrors(errors);
                        const firstError = Object.values(errors)[0];
                        toast.error(firstError || 'Error creating contact');
                        console.error('Error creating contact:', errors);
                    },
                });
            } else if (sidebarMode === 'edit' && activeContact) {
                const updatedContact = {
                    name: payload.name || activeContact.name,
                    primary_email: payload.primary_email || '',
                    primary_phone: payload.primary_phone || '',
                    is_login: payload.is_login || false,
                    password: payload.is_login ? payload.password || '' : '',
                    app_name: payload.app_name || 'main',
                    source: payload.source || 'lead',
                    assigned_to: payload.assigned_to || [],
                    contact_owner: payload.contact_owner ?? null,
                    type: payload.type ?? 1,
                    category: payload.category ?? 2, // 2 = Customer
                    status: payload.status ?? 1, // Use ?? to allow 0 (inactive) status
                };
                console.log('🚀 ~ ContactAddOnSidebar ~ updatedContact:', updatedContact);
                // @ts-ignore
                router.put(getPutRoute(activeContact?.uid!), updatedContact, {
                    onSuccess: () => {
                        // Notify global listeners to refresh
                        try {
                            toast.success('Contact updated successfully');
                            refreshContacts?.();
                        } catch {}
                        addOnClose();
                    },
                    onError: (errors: Record<string, string>) => {
                        setServerErrors(errors);
                        const firstError = Object.values(errors)[0];
                        toast.error(firstError || 'Error updating contact');
                        console.error('Error updating contact:', errors);
                    },
                });
            }
        },
        [sidebarMode, activeContact, module],
    );
    const getFilteredContacts = () => {
        let filtered = contacts;

        // Apply tab filter
        switch (activeTab) {
            case 'favorites':
                filtered = contacts.filter((contact) => contact.favorite);
                break;
            case 'recent':
                filtered = [...contacts]
                    .sort((a, b) => {
                        // Simple sorting logic for recent contacts based on lastContact
                        const aRecent = a.lastContact?.includes('hour') || a.lastContact?.includes('day') || false;
                        const bRecent = b.lastContact?.includes('hour') || b.lastContact?.includes('day') || false;

                        if (aRecent && !bRecent) return -1;
                        if (!aRecent && bRecent) return 1;
                        return 0;
                    })
                    .slice(0, 5);
                break;
            case 'all':
            default:
                filtered = contacts;
                break;
        }

        // Apply group filter
        if (groupFilter !== 'all') {
            filtered = filtered.filter((contact) => {
                const group = contact.group?.toLowerCase() || '';
                return group === groupFilter;
            });
        }

        // Apply search filter
        if (searchQuery) {
            filtered = filtered.filter(
                (contact) =>
                    contact.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    contact.primary_email.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    (contact.company && contact.company.toLowerCase().includes(searchQuery.toLowerCase())) ||
                    (contact.primary_phone && contact.primary_phone.toLowerCase().includes(searchQuery.toLowerCase())),
            );
        }

        return filtered;
    };

    const filteredContacts = getFilteredContacts();

    const getInitials = (name: string) => {
        return name
            .split(' ')
            .map((part) => part.charAt(0))
            .join('')
            .toUpperCase()
            .substring(0, 2);
    };

    return (
        <div className="flex h-full w-full flex-col bg-card">
            <div className="flex items-center justify-between border-b px-2 py-3">
                <div className="flex items-center gap-3 px-1">
                    {sidebarMode !== 'list' && (
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                                if (sidebarMode === 'edit') {
                                    addOnClose();
                                    return;
                                }
                                setSidebarMode('list');
                            }}
                            className="h-8 w-8 p-0"
                        >
                            <ArrowLeft className="h-4 w-4" />
                        </Button>
                    )}
                    <h2 className="text-xl font-semibold tracking-tight">
                        {sidebarMode === 'add'
                            ? 'Add ' + ' ' + title
                            : sidebarMode === 'edit'
                              ? 'Edit ' + ' ' + title
                              : sidebarMode === 'details'
                                ? 'Contact Details'
                                : title}
                    </h2>
                    {sidebarMode === 'list' && (
                        <Button
                            size="sm"
                            variant="outline"
                            onClick={() => {
                                setSidebarMode('add');
                                setActiveContact(null);
                            }}
                            className="size-5 rounded-full"
                        >
                            <Plus className="h-3 w-3" />
                        </Button>
                    )}
                </div>
                <div className="flex items-center gap-4">
                    {sidebarMode === 'list' && (
                        <div className="relative">
                            <Search className="absolute top-1/2 left-2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                            <input
                                type="text"
                                placeholder="Search..."
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="h-8 w-36 rounded-md border border-input bg-transparent pr-3 pl-8 text-sm"
                            />
                        </div>
                    )}
                    <Link href="/contacts">
                        <Button variant="ghost" size="sm" onClick={onClose} className="size-6">
                            <ExternalLinkIcon className="h-3 w-3 text-success" />
                        </Button>
                    </Link>
                    <Button variant="ghost" size="sm" onClick={addOnClose} className="size-6 rounded-full border">
                        <X className="h-3 w-3" />
                    </Button>
                </div>
            </div>

            {sidebarMode === 'list' && (
                <div className="border-b px-4">
                    <div className="flex gap-6">
                        {[
                            { key: 'all', label: 'All' },
                            { key: 'favorites', label: 'Favorites' },
                            { key: 'recent', label: 'Recent' },
                        ].map(({ key, label }) => (
                            <button
                                key={key}
                                onClick={() => setActiveTab(key as ActiveTab)}
                                className={cn(
                                    'relative py-3 text-sm font-medium transition-colors',
                                    activeTab === key
                                        ? 'text-foreground after:absolute after:right-0 after:bottom-0 after:left-0 after:h-0.5 after:bg-foreground'
                                        : 'text-muted-foreground hover:text-foreground',
                                )}
                            >
                                {label}
                            </button>
                        ))}
                    </div>
                </div>
            )}

            <div className="flex-1 overflow-auto px-2">
                {isLoadingContact ? (
                    <div className="flex h-52 flex-col items-center justify-center">
                        <Loader2 className="h-6 w-6 animate-spin text-primary" />
                        <p className="mt-4 text-sm text-muted-foreground">Loading contact details...</p>
                    </div>
                ) : sidebarMode === 'add' || sidebarMode === 'edit' ? (
                    <ContactForm
                        mode={sidebarMode === 'add' ? 'add' : 'edit'}
                        initialContact={activeContact}
                        onSubmitContact={handleContactSubmit}
                        onCancel={() => {
                            setSidebarMode('list');
                            setActiveContact(null);
                            setServerErrors({});
                        }}
                        title={title}
                        appName={appName}
                        serverErrors={serverErrors}
                    />
                ) : sidebarMode === 'details' && activeContact ? (
                    <ContactDetails contact={activeContact} mode="sidebar" />
                ) : filteredContacts.length === 0 ? (
                    <div className="flex h-52 flex-col items-center justify-center">
                        <div className="rounded-full bg-primary/10 p-3">
                            <Search className="h-6 w-6 text-primary" />
                        </div>
                        <p className="mt-4 text-sm font-medium">No contacts found</p>
                    </div>
                ) : (
                    <div className="space-y-3">
                        {filteredContacts.map((contact) => (
                            <div
                                key={contact.id}
                                className="group relative flex cursor-pointer items-center gap-3 border-b bg-card px-1 pb-2 hover:bg-accent/40"
                                onClick={() => {
                                    setActiveContact(contact);
                                    setSidebarMode('details');
                                }}
                            >
                                <Avatar className="h-10 w-10">
                                    {contact.avatar ? (
                                        <AvatarImage src={contact.avatar} alt={contact.name} />
                                    ) : (
                                        <AvatarFallback>{getInitials(contact.name)}</AvatarFallback>
                                    )}
                                </Avatar>

                                <div className="min-w-0 flex-1">
                                    <div className="flex items-center justify-between">
                                        <h3 className="truncate text-sm font-medium">{contact.name}</h3>
                                        <div className="flex items-center justify-between">
                                            {contact.group && (
                                                <div className="">
                                                    <span
                                                        className={cn(
                                                            'inline-block rounded-md border px-2 py-0.5 text-xs',
                                                            groupColors[contact.group] || 'bg-muted',
                                                        )}
                                                    >
                                                        {contact.group}
                                                    </span>
                                                </div>
                                            )}
                                            <div className="pl-2">
                                                {contact.favorite && <Star className="h-3 w-3 fill-amber-500 text-amber-500" />}
                                            </div>

                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                                                    <Button variant="ghost" size="sm" className="h-6 w-6 opacity-0 group-hover:opacity-100">
                                                        <MoreVertical className="h-3 w-3" />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            setContacts((prev) =>
                                                                prev.map((c) => (c.id === contact.id ? { ...c, favorite: !c.favorite } : c)),
                                                            );
                                                        }}
                                                    >
                                                        <Star className="mr-2 h-4 w-4" />
                                                        {contact.favorite ? 'Remove from favorites' : 'Add to favorites'}
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            handleEditContact(contact);
                                                        }}
                                                    >
                                                        <Pencil className="mr-2 h-4 w-4" />
                                                        Edit
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            setContacts((prev) => prev.filter((c) => c.id !== contact.id));
                                                        }}
                                                        className="text-destructive focus:text-destructive"
                                                    >
                                                        <Trash className="mr-2 h-4 w-4" />
                                                        Delete
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </div>
                                    </div>

                                    <div className="flex flex-col text-xs text-muted-foreground">
                                        <div className="flex items-center gap-1">
                                            <Mail className="h-3 w-3" />
                                            <span className="truncate">{contact.primary_email}</span>
                                        </div>
                                        {/* <div className="flex items-baseline gap-2">
                                            <Button className="w-20 py-0" variant="outline" size={'sm'}>
                                                Mail
                                            </Button>
                                            <Button className="w-20" variant="outline" size={'sm'}>
                                                Message
                                            </Button>
                                        </div> */}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}

export default ContactAddOnSidebar;
