import { mockEmails, mockTasks } from '@admin/data/static';
import axios from 'axios';
import { toast } from 'sonner';
import EmailAddOnSidebar from '../addOns/addon-sidebars/emails/emails-sidebar';
import { EventAddOnSidebar } from '../addOns/addon-sidebars/events/events-sidebar';
import NoteAddOnSidebar from '../addOns/addon-sidebars/notes/notes-sidebar';
import ReminderSidebar from '../addOns/addon-sidebars/reminders/reminders-sidebar';
import { TaskAddOnSidebar } from '../addOns/addon-sidebars/tasks/tasks-sidebar';
import { TimelineGroup, TimelineItem } from './types';

interface TimelineHandlersProps {
    timelineData: TimelineGroup[];
    setTimelineData: React.Dispatch<React.SetStateAction<TimelineGroup[]>>;
    addOnOpen: (sidebar: { id: string; content: React.ReactNode }) => void;
    addOnClose: () => void;
}

export const createTimelineHandlers = ({ timelineData, setTimelineData, addOnOpen, addOnClose }: TimelineHandlersProps) => {
    const onTaskDelete = (id: number) => {
        // Find the activity log item to get its ID
        const activityItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        console.log('onDelete called with id:', id, 'activityItem:', activityItem);

        if (!activityItem) {
            toast.error('Activity not found');
            return;
        }

        // Confirm deletion
        if (!confirm('Are you sure you want to delete this activity? This action cannot be undone.')) {
            return;
        }

        // Make API call to delete the activity log
        const routeName = 'activity-log.destroy';
        const routeParams = { activityLog: activityItem.id };
        const routeUrl = route(routeName, routeParams);
        console.log('Making delete request to:', routeUrl, 'with params:', routeParams);

        // Log the full URL construction
        console.log('Route name:', routeName);
        console.log('Route params:', routeParams);
        console.log('Generated URL:', routeUrl);

        axios
            .delete(routeUrl)
            .then((response) => {
                console.log('Delete response:', response);
                if (response.data.success) {
                    // Update UI by removing the item from all groups
                    setTimelineData((prevData) =>
                        prevData.map((group) => ({
                            ...group,
                            items: group.items.filter((item: TimelineItem) => item.id !== id),
                        })),
                    );
                    toast.success(response.data.message);
                } else {
                    toast.error(response.data.message);
                }
            })
            .catch((error) => {
                console.error('Error deleting activity:', error);
                console.error('Error response:', error.response);
                if (error.response) {
                    console.error('Error response data:', error.response.data);
                    console.error('Error response status:', error.response.status);
                    console.error('Error response headers:', error.response.headers);
                }
                toast.error('Failed to delete activity: ' + (error.response?.data?.message || error.message));
            });
    };

    const onTaskEdit = (id: number) => {
        // Find the task item by id from all groups
        const taskItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!taskItem) {
            toast.error('Task not found');
            return;
        }

        // Map the timeline item to the task format expected by TaskAddOnSidebar
        const initialTask = {
            id: taskItem.id,
            title: taskItem.title,
            description: taskItem.description || '',
            priority: 'high', // You can extract this from metadata or set default
            status: 'in-progress', // You can extract this from metadata or set default
            due_date: (taskItem.metadata?.find((m: any) => m.label === 'Due Date')?.value as string) || '',
        };

        const sidebar = {
            id: 'task',
            content: <TaskAddOnSidebar mode="edit" initialTask={initialTask} onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onNoteEdit = (id: number) => {
        // Find the note item by id from all groups
        const noteItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!noteItem) {
            toast.error('Note not found');
            return;
        }

        // Map timeline item to Note interface
        const initialNote = {
            id: noteItem.id,
            uid: `note-${noteItem.id}`,
            title: noteItem.title,
            content: noteItem.description || '',
            tag: 'Work',
            is_pinned: noteItem.isPinned || false,
            is_favorite: false,
            created_by: 1,
            creator: noteItem.metadata?.[0]
                ? {
                      id: 1,
                      name: String(noteItem.metadata[0].value),
                      avatar: null,
                  }
                : undefined,
            followers: [],
            people: [],
            status: 1,
            status_name: 'ACTIVE',
            relation_type: null,
            relation_id: null,
            created_at: noteItem.timestamp,
            updated_at: noteItem.timestamp,
            favorites: false,
            deleted: false,
        };

        const sidebar = {
            id: 'note',
            content: <NoteAddOnSidebar mode="edit" initialNote={initialNote} onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onEmailEdit = (id: number) => {
        const emailItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!emailItem) {
            toast.error('Email not found');
            return;
        }

        // TODO: Map emailItem to proper Email interface when available
        const sidebar = {
            id: 'email',
            content: <EmailAddOnSidebar mode="compose" onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onReminderEdit = (id: number) => {
        const reminderItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!reminderItem) {
            toast.error('Reminder not found');
            return;
        }

        const sidebar = {
            id: 'reminder',
            content: <ReminderSidebar mode="edit" onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onEventEdit = (id: number) => {
        const eventItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!eventItem) {
            toast.error('Event not found');
            return;
        }

        // TODO: Map eventItem to proper Event interface when available
        const sidebar = {
            id: 'event',
            content: <EventAddOnSidebar mode="edit" onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onTaskView = (id: number) => {
        const taskItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!taskItem) {
            toast.error('Task not found');
            return;
        }

        const initialTask = {
            id: taskItem.id,
            title: taskItem.title,
            description: taskItem.description || '',
            priority: 'high',
            status: 'in-progress',
            due_date: (taskItem.metadata?.find((m: any) => m.label === 'Due Date')?.value as string) || '',
        };

        const sidebar = {
            id: 'task',
            content: <TaskAddOnSidebar mode="details" initialTask={mockTasks[0]} onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onNoteView = (id: number) => {
        const noteItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!noteItem) {
            toast.error('Note not found');
            return;
        }

        // Map timeline item to Note interface
        const initialNote = {
            id: noteItem.id,
            uid: `note-${noteItem.id}`,
            title: noteItem.title,
            content: noteItem.description || '',
            tag: 'Work',
            is_pinned: noteItem.isPinned || false,
            is_favorite: false,
            created_by: 1,
            creator: noteItem.metadata?.[0]
                ? {
                      id: 1,
                      name: String(noteItem.metadata[0].value),
                      avatar: null,
                  }
                : undefined,
            followers: [],
            people: [],
            status: 1,
            status_name: 'ACTIVE',
            relation_type: null,
            relation_id: null,
            created_at: noteItem.timestamp,
            updated_at: noteItem.timestamp,
            favorites: false,
            deleted: false,
        };

        const sidebar = {
            id: 'note',
            content: <NoteAddOnSidebar mode="details" initialNote={initialNote} onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onEmailView = (id: number) => {
        const emailItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!emailItem) {
            toast.error('Email not found');
            return;
        }

        // TODO: Map emailItem to proper Email interface when available
        const sidebar = {
            id: 'email',
            content: <EmailAddOnSidebar mode="details" initialEmail={mockEmails[0]} onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onReminderView = (id: number) => {
        const reminderItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!reminderItem) {
            toast.error('Reminder not found');
            return;
        }

        const sidebar = {
            id: 'reminder',
            content: <ReminderSidebar mode="details" onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const onEventView = (id: number) => {
        const eventItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!eventItem) {
            toast.error('Event not found');
            return;
        }

        // TODO: Map eventItem to proper Event interface when available
        const sidebar = {
            id: 'event',
            content: <EventAddOnSidebar mode="details" onClose={addOnClose} />,
        };

        addOnOpen(sidebar);
    };

    const handleEditByType = (id: number, type: string) => {
        switch (type) {
            case 'task':
                onTaskEdit(id);
                break;
            case 'note':
                onNoteEdit(id);
                break;
            case 'email':
                onEmailEdit(id);
                break;
            case 'reminder':
                onReminderEdit(id);
                break;
            case 'meeting':
            case 'events':
                onEventEdit(id);
                break;
            default:
                toast.error('Unknown item type');
        }
    };

    const handleViewByType = (id: number, type: string) => {
        switch (type) {
            case 'task':
                onTaskView(id);
                break;
            case 'note':
                onNoteView(id);
                break;
            case 'email':
                onEmailView(id);
                break;
            case 'reminder':
                onReminderView(id);
                break;
            case 'meeting':
            case 'events':
                onEventView(id);
                break;
            default:
                toast.error('Unknown item type');
        }
    };

    const onTaskPin = (id: number) => {
        // Find the activity item to get its type
        const activityItem = timelineData.flatMap((group) => group.items).find((item) => item.id === id);

        if (!activityItem) {
            toast.error('Activity not found');
            return;
        }

        // Determine if we're pinning or unpinning
        const isCurrentlyPinned = activityItem.isPinned || false;
        const action = isCurrentlyPinned ? 'unpin' : 'pin';

        // Determine the route based on the item type
        let routeName = `activity-log.${action}`;

        // Use specific routes for note, task, and reminder types
        if (activityItem.type === 'note') {
            routeName = `note.${action}`;
        } else if (activityItem.type === 'task') {
            routeName = `task.${action}`;
        } else if (activityItem.type === 'reminder') {
            routeName = `reminder.${action}`;
        } else if (activityItem.type === 'email') {
            routeName = `email.${action}`;
        } else if (activityItem.type === 'call') {
            routeName = `call.${action}`;
        } else if (activityItem.type === 'meeting') {
            routeName = `meeting.${action}`;
        }

        // Make API call to pin/unpin
        axios
            .post(route(routeName, activityItem.id))
            .then((response) => {
                if (response.data.success) {
                    // Update UI by toggling the pinned status in all groups
                    setTimelineData((prevData) =>
                        prevData.map((group) => ({
                            ...group,
                            items: group.items.map((item: TimelineItem) => (item.id === id ? { ...item, isPinned: !isCurrentlyPinned } : item)),
                        })),
                    );
                    toast.success(response.data.message);
                } else {
                    toast.error(response.data.message);
                }
            })
            .catch((error) => {
                console.error(`Error ${action}ning ${activityItem.type}:`, error);
                toast.error(`Failed to ${action} ${activityItem.type}`);
            });
    };

    return {
        onTaskDelete,
        onTaskEdit,
        onNoteEdit,
        onEmailEdit,
        onReminderEdit,
        onEventEdit,
        onTaskView,
        onNoteView,
        onEmailView,
        onReminderView,
        onEventView,
        handleEditByType,
        handleViewByType,
        onTaskPin,
    };
};
