import { NoteDetails } from '@admin/components/addOns/addon-sidebars/notes/NoteDetails';
import NoteForm, { NormalizedNotePayload } from '@admin/components/addOns/addon-sidebars/notes/NoteForm';
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, usePage } from '@inertiajs/react';
import axios from 'axios';
import { ArrowLeft, Calendar, ExternalLinkIcon, Loader2, MoreVertical, Pencil, Pin, Plus, Search, Star, Trash, X } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';

export interface Note {
    id: number;
    uid: string;
    title: string;
    content: string;
    tag?: string;
    is_pinned: boolean;
    is_favorite?: boolean;
    created_by: number;
    creator?: {
        id: number;
        name: string;
        avatar?: string | null;
    };
    followers?: Array<{
        id: number;
        name: string;
        avatar?: string | null;
    }>;
    people?: number[]; // Array of follower IDs
    status: number;
    status_name: string;
    notable_type: string | null;
    notable_id: number | null;
    created_at: string;
    updated_at: string;
    favorites?: boolean;
    deleted?: boolean;
}

const statusColors: Record<string, string> = {
    ACTIVE: 'bg-green-50 text-green-700 border-green-200',
    FAVORITE: 'bg-amber-50 text-amber-700 border-amber-200',
    ARCHIVED: 'bg-gray-50 text-gray-700 border-gray-200',
};

type ActiveTab = 'all' | 'favorites' | 'trash';

interface NoteAddOnSidebarProps {
    title?: string;
    onClose?: () => void;
    isOpen?: boolean;
    notableType?: string | null;
    notableId?: number | null;
    initialNote?: Note | null;
    onSuccess?: () => void;
    forceMode?: 'add' | 'edit';
    refetchNotes?: any;
    contactAbleType?: string | null;
    contactId?: number | null;
    mode?: 'list' | 'add' | 'edit' | 'details';
}

export function NoteAddOnSidebar({
    title = 'Notes',
    onClose,
    isOpen = true,
    notableType,
    notableId,
    initialNote,
    onSuccess,
    forceMode,
    mode = 'list',
    refetchNotes,
    contactAbleType,
    contactId,
}: NoteAddOnSidebarProps) {
    const page = usePage();
    const { addOnClose } = useAddOn();
    const [searchQuery, setSearchQuery] = useState('');
    const [activeTab, setActiveTab] = useState<ActiveTab>('all');
    const relationType = contactAbleType;
    const [sidebarMode, setSidebarMode] = useState<'list' | 'add' | 'edit' | 'details'>(mode);

    // Debug: Log the props received
    console.log('🔍 NoteAddOnSidebar props:', {
        contactAbleType,
        contactId,
        relationType,
    });
    const [notes, setNotes] = useState<Note[]>([]);
    const [activeNote, setActiveNote] = useState<Note | null>(initialNote || null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [users, setUsers] = useState<any[]>([]);
    const [statuses, setStatuses] = useState<any[]>([]);
    const [noteTags, setNoteTags] = useState<any[]>([]);

    // When forceMode is set, open directly in that mode
    useEffect(() => {
        if (forceMode) {
            setSidebarMode(forceMode);
            if (forceMode === 'edit' && initialNote) {
                setActiveNote(initialNote);
            } else if (forceMode === 'add') {
                setActiveNote(null);
            }
        }
    }, [forceMode, initialNote]);

    // Fetch notes from API
    const fetchNotes = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await axios.get('/notes', {
                headers: {
                    Accept: 'application/json',
                },
                params: {
                    per_page: 100,
                    tab: activeTab, // Send active tab to backend for filtering
                },
            });
            setNotes(response.data.data || []);
            setUsers(response.data.users || []);
            setStatuses(response.data.statuses || []);
            setNoteTags(response.data.noteTags || []);
        } catch (err: any) {
            setError(err.response?.data?.message || 'Failed to load notes');
            console.error('Error fetching notes:', err);
        } finally {
            setLoading(false);
        }
    }, [activeTab]);

    useEffect(() => {
        fetchNotes();
    }, [fetchNotes]);

    const handleNoteSubmit = useCallback(
        async (payload: NormalizedNotePayload) => {
            try {
                if (sidebarMode === 'add') {
                    const postData = {
                        title: payload.title || 'Untitled',
                        content: payload.description || '',
                        tags: payload.tags || [],
                        date: payload.date || null,
                        people: payload.people || [],
                        note_type: 1, // TEXT
                        status: 1, // ACTIVE
                        is_pinned: false,
                        relation_type: relationType || null,
                        relation_id: contactId || null,
                    };
                    console.log('🚀 ~ NoteAddOnSidebar ~ postData:', postData);
                    await axios.post('/notes', postData);
                    toast.success('Note created successfully');
                } else if (sidebarMode === 'edit' && activeNote) {
                    const updateData = {
                        title: payload.title || activeNote.title,
                        content: payload.description || activeNote.content,
                        tags: payload.tags || [],
                        date: payload.date || null,
                        people: payload.people || [],
                        is_pinned: activeNote.is_pinned,
                        note_type: 1,
                        status: 1,
                        relation_type: relationType || null,
                        relation_id: contactId || null,
                    };
                    await axios.put(`/notes/${activeNote.id}`, updateData);
                    toast.success('Note updated successfully');
                }
                addOnClose();
                await fetchNotes();

                refetchNotes();
                addOnClose();
                // if (page.url == '/notes') {
                // }

                // If standalone mode, call onSuccess and onClose
                if (isStandalone) {
                    onSuccess?.();
                    onClose?.();
                } else {
                    setSidebarMode('list');
                    setActiveNote(null);
                }
            } catch (err: any) {
                console.error('Error saving note:', err);
                const errorMessage = err.response?.data?.message || 'Failed to save note';
                setError(errorMessage);
                toast.error(errorMessage);
            }
        },
        [sidebarMode, activeNote, fetchNotes, notableType, notableId, onSuccess, onClose, forceMode],
    );

    const getFilteredNotes = () => {
        let filtered = notes;

        // Backend already filters by tab, so we only need to apply search filter
        // Apply search filter
        if (searchQuery) {
            filtered = filtered.filter(
                (note) =>
                    note.title?.toLowerCase().includes(searchQuery.toLowerCase()) || note.content?.toLowerCase().includes(searchQuery.toLowerCase()),
            );
        }

        return filtered;
    };

    const filteredNotes = getFilteredNotes();

    // Support controlled visibility for standalone usage
    if (!isOpen) return null;

    // Standalone mode: fixed overlay from right (when forceMode is used)
    const isStandalone = !!forceMode;

    return (
        <>
            {isStandalone && <div className="fixed inset-0 z-40 bg-black/50" onClick={onClose} />}
            <div className={cn('flex flex-col bg-card', isStandalone ? 'fixed inset-y-0 right-0 z-50 w-full border-l shadow-lg' : 'h-full w-full')}>
                <div className="flex items-center justify-between border-b px-2 py-3">
                    <div className="flex items-center gap-3 px-1">
                        {sidebarMode !== 'list' && !isStandalone && (
                            <Button variant="ghost" size="sm" onClick={() => 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 Note'
                                : sidebarMode === 'edit'
                                  ? 'Edit Note'
                                  : sidebarMode === 'details'
                                    ? 'Note Details'
                                    : title}
                        </h2>
                        {sidebarMode === 'list' && (
                            <Button
                                size="sm"
                                variant="outline"
                                onClick={() => {
                                    setSidebarMode('add');
                                    setActiveNote(null);
                                }}
                                className="size-5 rounded-full"
                            >
                                <Plus className="h-3 w-3" />
                            </Button>
                        )}
                    </div>

                    <div className="flex items-center gap-2">
                        {sidebarMode === 'list' && !isStandalone && (
                            <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-62 rounded-md border border-input bg-transparent pr-3 pl-8 text-sm"
                                />
                            </div>
                        )}
                        {!isStandalone && (
                            <>
                                <Link href="/tools/tasks">
                                    <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>
                            </>
                        )}
                        {isStandalone && (
                            <Button variant="ghost" size="sm" onClick={onClose} className="h-8 w-8 p-0">
                                <X className="h-4 w-4" />
                            </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: 'trash', label: 'Trash' },
                            ].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 p-2">
                    {loading ? (
                        <div className="flex h-full flex-col items-center justify-center text-center">
                            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                            <p className="mt-4 text-sm text-muted-foreground">Loading notes...</p>
                        </div>
                    ) : error ? (
                        <div className="flex h-full flex-col items-center justify-center text-center">
                            <div className="rounded-full bg-destructive/10 p-4">
                                <X className="h-6 w-6 text-destructive" />
                            </div>
                            <p className="mt-4 text-sm font-medium text-destructive">{error}</p>
                            <Button onClick={fetchNotes} variant="outline" size="sm" className="mt-4">
                                Retry
                            </Button>
                        </div>
                    ) : sidebarMode === 'add' || sidebarMode === 'edit' ? (
                        <NoteForm
                            mode={sidebarMode === 'add' ? 'add' : 'edit'}
                            initialNote={activeNote}
                            onSubmitNote={handleNoteSubmit}
                            onCancel={() => {
                                setSidebarMode('list');
                                setActiveNote(null);
                            }}
                            users={users}
                            statuses={statuses}
                            noteTags={noteTags}
                        />
                    ) : sidebarMode === 'details' && activeNote ? (
                        <NoteDetails
                            note={{
                                ...activeNote,
                                description: activeNote.content,
                                date: new Date(activeNote.created_at).toLocaleDateString(),
                                tag: activeNote.status_name,
                                people: activeNote.creator ? [activeNote.creator.avatar || ''] : [],
                                color: '#1f8ef1',
                            }}
                            mode="sidebar"
                        />
                    ) : filteredNotes.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 notes found</p>
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {filteredNotes.map((note) => (
                                <div
                                    key={note.id}
                                    className="group relative flex cursor-pointer flex-col gap-2 border-b bg-card px-3 pb-2 hover:bg-accent/40"
                                    onClick={() => {
                                        setActiveNote(note);
                                        setSidebarMode('details');
                                    }}
                                >
                                    <div className="flex items-center justify-between">
                                        <div className="flex items-center gap-2">
                                            <span className="h-3 w-3 rounded-full bg-blue-500"></span>
                                            <h3 className="text-base font-medium">{note.title}</h3>
                                        </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" className="w-[180px]">
                                                <DropdownMenuItem
                                                    onClick={async (e) => {
                                                        e.stopPropagation();
                                                        try {
                                                            await axios.put(
                                                                `/notes/${note.id}`,
                                                                {
                                                                    is_pinned: !note.is_pinned,
                                                                },
                                                                {
                                                                    headers: {
                                                                        Accept: 'application/json',
                                                                        'Content-Type': 'application/json',
                                                                    },
                                                                },
                                                            );
                                                            await fetchNotes();
                                                        } catch (err) {
                                                            console.error('Error updating note:', err);
                                                        }
                                                    }}
                                                >
                                                    <Pin className="mr-2 h-3.5 w-3.5" />
                                                    {note.is_pinned ? 'Unpin note' : 'Pin note'}
                                                </DropdownMenuItem>
                                                <DropdownMenuItem
                                                    onClick={async (e) => {
                                                        e.stopPropagation();
                                                        try {
                                                            const isFavorite = note.status === 19 || note.status_name === 'FAVORITE';
                                                            const newStatus = isFavorite ? 1 : 19;
                                                            await axios.put(
                                                                `/notes/${note.id}`,
                                                                {
                                                                    status: newStatus,
                                                                },
                                                                {
                                                                    headers: {
                                                                        Accept: 'application/json',
                                                                        'Content-Type': 'application/json',
                                                                    },
                                                                },
                                                            );
                                                            await fetchNotes();
                                                        } catch (err) {
                                                            console.error('Error updating note:', err);
                                                        }
                                                    }}
                                                >
                                                    <Star className="mr-2 h-3.5 w-3.5 fill-amber-400" />
                                                    {note.status === 19 || note.status_name === 'FAVORITE'
                                                        ? 'Remove from favorites'
                                                        : 'Add to favorites'}
                                                </DropdownMenuItem>
                                                {!(note.status === 11 || note.status_name === 'ARCHIVED') && (
                                                    <DropdownMenuItem
                                                        onClick={async (e) => {
                                                            e.stopPropagation();
                                                            try {
                                                                // Fetch full note data with all relationships
                                                                const response = await axios.get(`/notes/${note.id}`, {
                                                                    headers: {
                                                                        Accept: 'application/json',
                                                                    },
                                                                });
                                                                setActiveNote(response.data.data || note);
                                                                setSidebarMode('edit');
                                                            } catch (err) {
                                                                console.error('Error fetching note:', err);
                                                                // Fallback to using note from list
                                                                setActiveNote(note);
                                                                setSidebarMode('edit');
                                                            }
                                                        }}
                                                    >
                                                        <Pencil className="mr-2 h-3.5 w-3.5" />
                                                        Edit
                                                    </DropdownMenuItem>
                                                )}
                                                {(note.status === 11 || note.status_name === 'ARCHIVED') && (
                                                    <DropdownMenuItem
                                                        onClick={async (e) => {
                                                            e.stopPropagation();
                                                            try {
                                                                await axios.put(
                                                                    `/notes/${note.id}`,
                                                                    {
                                                                        status: 1,
                                                                    },
                                                                    {
                                                                        headers: {
                                                                            Accept: 'application/json',
                                                                            'Content-Type': 'application/json',
                                                                        },
                                                                    },
                                                                );
                                                                await fetchNotes();
                                                            } catch (err) {
                                                                console.error('Error restoring note:', err);
                                                            }
                                                        }}
                                                    >
                                                        <ArrowLeft className="mr-2 h-3.5 w-3.5" />
                                                        Restore
                                                    </DropdownMenuItem>
                                                )}
                                                <DropdownMenuItem
                                                    onClick={async (e) => {
                                                        e.stopPropagation();
                                                        try {
                                                            const isArchived = note.status === 11 || note.status_name === 'ARCHIVED';
                                                            if (isArchived) {
                                                                // Permanently delete
                                                                await axios.delete(`/notes/${note.id}`, {
                                                                    headers: {
                                                                        Accept: 'application/json',
                                                                    },
                                                                });
                                                            } else {
                                                                // Move to trash (archive)
                                                                await axios.put(
                                                                    `/notes/${note.id}`,
                                                                    {
                                                                        status: 11,
                                                                    },
                                                                    {
                                                                        headers: {
                                                                            Accept: 'application/json',
                                                                            'Content-Type': 'application/json',
                                                                        },
                                                                    },
                                                                );
                                                            }
                                                            await fetchNotes();
                                                        } catch (err) {
                                                            console.error('Error deleting note:', err);
                                                        }
                                                    }}
                                                    className="text-destructive focus:text-destructive"
                                                >
                                                    <Trash className="mr-2 h-3.5 w-3.5" />
                                                    {note.status === 11 || note.status_name === 'ARCHIVED' ? 'Delete permanently' : 'Move to trash'}
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className={cn('rounded-md border px-2 py-0.5 text-xs', statusColors[note.status_name] || 'bg-muted')}>
                                            {note.status_name}
                                        </span>
                                        <span className="flex items-center gap-1 text-xs text-muted-foreground">
                                            <Calendar className="h-3 w-3" />
                                            {new Date(note.created_at).toLocaleDateString()}
                                        </span>
                                    </div>
                                    <p className="line-clamp-2 text-xs text-muted-foreground">{note.content}</p>
                                    {note.creator && (
                                        <div className="flex -space-x-2">
                                            <Avatar className="size-6 border-2 border-background">
                                                <AvatarImage src={note.creator.avatar || ''} />
                                                <AvatarFallback>{note.creator.name.charAt(0)}</AvatarFallback>
                                            </Avatar>
                                        </div>
                                    )}
                                    {note.is_pinned && <Pin className="absolute top-7 right-4 h-3 w-3 fill-blue-500 text-blue-500" />}
                                    {(note.status === 19 || note.status_name === 'FAVORITE') && (
                                        <Star className="absolute top-7 right-10 h-3 w-3 fill-amber-500 text-amber-500" />
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

export default NoteAddOnSidebar;
