import GeneralHeader from '@admin/components/general-header';
import NoteAddModal from '@admin/components/modals/note-add-modal';
import { Avatar, AvatarFallback, AvatarImage } from '@admin/components/ui/avatar';
import { Badge } from '@admin/components/ui/badge';
import { Button } from '@admin/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@admin/components/ui/dropdown-menu';
import { Input } from '@admin/components/ui/input';
import { mockNotes } from '@admin/data/static';
import AppLayout from '@admin/layouts/app-layout';
import { cn } from '@admin/lib/utils';
import type { PaginatedData } from '@admin/types';
import { Head } from '@inertiajs/react';
import { CalendarIcon, EditIcon, Heart, Notebook, Plus, Trash2 } from 'lucide-react';
import { ReactNode, useState } from 'react';

export interface Note {
    id: string;
    title: string;
    description: string;
    date: string;
    tag: 'Personal' | 'Work' | 'Social' | 'Important' | 'High';
    people: string[];
    bullets: string[];
    favorites?: boolean;
    color?: string;
}

const tagColors = {
    Personal: 'bg-blue-100 text-blue-800 border-blue-200',
    Work: 'bg-orange-100 text-orange-800 border-orange-200',
    Social: 'bg-purple-100 text-purple-800 border-purple-200',
    Important: 'bg-red-100 text-red-800 border-red-200',
    High: 'bg-red-100 text-red-800 border-red-200',
};

const tagCounts = {
    Team: 18,
    Update: 22,
    Low: 16,
    Medium: 5,
    High: 2,
};

type ActiveTab = 'all' | 'favorites' | 'chats' | 'trash';
function Index() {
    const [searchQuery, setSearchQuery] = useState('');
    const [activeTab, setActiveTab] = useState<ActiveTab>('all');
    const [isAddNoteModalOpen, setIsAddNoteModalOpen] = useState(false);
    const [modalMode, setModalMode] = useState<'add' | 'edit'>('add');
    const [notes, setNotes] = useState<Note[]>(mockNotes);
    const [editingNote, setEditingNote] = useState<Note | null>(null);

    const getFilteredTasks = () => {
        let filtered = mockNotes;

        switch (activeTab) {
            case 'favorites':
                filtered = mockNotes.filter((note) => note.favorites);
                break;
            case 'chats':
            default:
                filtered = mockNotes;
                break;
        }

        if (searchQuery) {
            filtered = filtered.filter(
                (note) =>
                    note.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    note.description.toLowerCase().includes(searchQuery.toLowerCase()),
            );
        }

        return filtered;
    };

    const filteredNotes = getFilteredTasks();

    // Create a client-side paginatedData object for the DataTable
    const perPage = 10;
    const currentPage = 1;
    const total = filteredNotes.length;
    const lastPage = Math.max(1, Math.ceil(total / perPage));
    const paginatedData: PaginatedData<Note> = {
        data: filteredNotes.slice((currentPage - 1) * perPage, currentPage * perPage),
        queryParams: { page: currentPage, per_page: perPage },
        meta: {
            from: total === 0 ? 0 : (currentPage - 1) * perPage + 1,
            to: Math.min(total, currentPage * perPage),
            total: total,
            current_page: currentPage,
            last_page: lastPage,
        },
        links: {
            prev: currentPage > 1 ? 'prev' : null,
            next: currentPage < lastPage ? 'next' : null,
        },
        userSummary: [],
    };

    return (
        <div className="flex h-full w-full flex-col bg-card">
            <Head title="Notes" />
            <div className="border-b border-gray-200 bg-card">
                <GeneralHeader title="Notes" description="Manage your notes efficiently" page="Notes" />
            </div>
            <div className="flex h-full min-h-0 flex-1 flex-col items-stretch overflow-hidden md:flex-row md:items-start">
                {/* Mobile: compact dropdown for small screens */}
                <div className="flex w-96 items-center justify-between border-b border-muted bg-background p-2 md:hidden md:w-full">
                    <div className="flex items-center gap-2">
                        <Button size="sm" variant="ghost" className="flex items-center" onClick={() => setIsAddNoteModalOpen(true)}>
                            <Plus className="mr-2 h-4 w-4" />
                            Add New Note
                        </Button>
                    </div>

                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button size="sm">Filters</Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-64">
                            <div className="p-2">
                                <div className="space-y-2">
                                    <div
                                        className={cn(
                                            'flex cursor-pointer items-center justify-between rounded-lg p-2',
                                            activeTab === 'all' ? 'bg-muted' : 'hover:bg-background',
                                        )}
                                        onClick={() => setActiveTab('all')}
                                    >
                                        <div className="flex items-center gap-2">
                                            <div className="h-2 w-2 rounded-full bg-blue-500"></div>
                                            <span className="text-sm font-medium">All Tasks</span>
                                        </div>
                                    </div>

                                    <div
                                        className={cn(
                                            'flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2',
                                            activeTab === 'chats' ? 'bg-muted' : 'hover:bg-background',
                                        )}
                                        onClick={() => setActiveTab('chats')}
                                    >
                                        <Notebook />
                                        <span className="text-sm">Chats</span>
                                    </div>

                                    <div
                                        className={cn(
                                            'flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2',
                                            activeTab === 'trash' ? 'bg-muted' : 'hover:bg-background',
                                        )}
                                        onClick={() => setActiveTab('trash')}
                                    >
                                        <div className="flex h-4 w-4 items-center justify-center">🗑️</div>
                                        <span className="text-sm">Trash</span>
                                    </div>
                                </div>

                                <div className="space-y-3">
                                    <h3 className="text-sm font-medium text-gray-900">Tags</h3>
                                    <div className="space-y-2">
                                        {Object.entries(tagCounts).map(([tag, count]) => (
                                            <div key={tag} className="flex items-center justify-between">
                                                <Badge
                                                    variant="secondary"
                                                    className={cn(
                                                        'text-xs font-medium',
                                                        tag === 'Team' && 'bg-blue-100 text-blue-800',
                                                        tag === 'Update' && 'bg-cyan-100 text-cyan-800',
                                                        tag === 'Low' && 'bg-success-100 text-success-800',
                                                        tag === 'Medium' && 'bg-purple-100 text-purple-800',
                                                        tag === 'High' && 'bg-red-100 text-red-800',
                                                    )}
                                                >
                                                    {tag}
                                                </Badge>
                                                <span className="rounded-full bg-gray-100 px-2 py-1 text-xs text-gray-500">{count}</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>

                {/* Sidebar */}
                <div className="sticky top-0 hidden h-full w-80 flex-col self-start overflow-y-auto border-r border-muted bg-background md:flex">
                    {/* Header */}
                    <div className="space-y-3 p-4">
                        <Button className="w-full" onClick={() => setIsAddNoteModalOpen(true)}>
                            <Plus className="mr-2 h-4 w-4" />
                            Add New Note
                        </Button>
                        <Input placeholder="Search" className="" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
                    </div>

                    {/* Navigation */}
                    <div className="space-y-4 px-4">
                        <div className="space-y-2">
                            <div
                                className={cn(
                                    'flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2',
                                    activeTab === 'chats' ? 'bg-muted' : 'hover:bg-background',
                                )}
                                onClick={() => setActiveTab('chats')}
                            >
                                <div className="flex h-4 w-4 items-center justify-center">
                                    <Notebook color="gray" />
                                </div>
                                <span className="text-sm">Chats</span>
                            </div>
                            <div
                                className={cn(
                                    'flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2',
                                    activeTab === 'trash' ? 'bg-muted' : 'hover:bg-background',
                                )}
                                onClick={() => setActiveTab('trash')}
                            >
                                <div className="flex h-4 w-4 items-center justify-center">🗑️</div>
                                <span className="text-sm">Trash</span>
                            </div>
                        </div>
                        {/* Tags */}
                        <div className="space-y-5">
                            <h3 className="text-sm font-medium text-gray-900">Tags</h3>
                            <div className="space-y-5">
                                {Object.entries(tagCounts).map(([tag, count]) => (
                                    <div key={tag} className="flex items-center justify-between">
                                        <Badge
                                            variant="secondary"
                                            className={cn(
                                                'text-xs font-medium',
                                                tag === 'Team' && 'bg-blue-100 text-blue-800',
                                                tag === 'Update' && 'bg-cyan-100 text-cyan-800',
                                                tag === 'Low' && 'bg-success-100 text-success-800',
                                                tag === 'Medium' && 'bg-purple-100 text-purple-800',
                                                tag === 'High' && 'bg-red-100 text-red-800',
                                            )}
                                        >
                                            {tag}
                                        </Badge>
                                        <span className="rounded-full bg-gray-100 px-2 py-1 text-xs text-gray-500">{count}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Notes Grid */}
                <div className="no-scrollbar h-full min-h-0 flex-1 overflow-y-auto p-2 md:p-4 lg:p-6">
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
                        {filteredNotes.map((note) => (
                            <div
                                key={note.id}
                                className="flex w-96 flex-col justify-between rounded-2xl border border-gray-200 bg-card p-4 transition-shadow hover:shadow-md md:w-full"
                                style={{ borderTop: `3px solid ${note.color}` }}
                            >
                                <div className="">
                                    {/* Card Header */}
                                    <div className="mb-4 flex flex-col items-start justify-between border-b pb-4 sm:flex-row sm:items-center">
                                        <Badge className={cn('border text-xs font-medium', tagColors[note.tag])}>{note.tag}</Badge>
                                        <div className="flex items-center gap-2">
                                            <EditIcon
                                                className="h-4 w-4 cursor-pointer"
                                                color="gray"
                                                onClick={() => {
                                                    setEditingNote(note);
                                                    setModalMode('edit');
                                                    setIsAddNoteModalOpen(true);
                                                }}
                                            />
                                        </div>
                                    </div>

                                    {/* Card Content */}
                                    <div className="space-y-4">
                                        <h3 className="text-lg leading-tight font-semibold">{note.title}</h3>

                                        {/* Bullet Points */}
                                        <div className="space-y-1">
                                            {note.bullets.map((bullet, index) => (
                                                <div key={index} className="flex items-center gap-2 text-sm">
                                                    <div className="h-1 w-1 flex-shrink-0 rounded-full bg-gray-700"></div>
                                                    <span>{bullet}</span>
                                                </div>
                                            ))}
                                        </div>

                                        {/* Description */}
                                        <p className="text-sm leading-relaxed">{note.description}</p>
                                    </div>
                                </div>

                                {/* Card Footer */}
                                <div className="mt-6 flex items-center justify-between border-t border-gray-100 pt-4">
                                    <div className="flex items-center gap-2">
                                        <CalendarIcon className="h-3 w-3" />
                                        <span className="text-xs">{note.date}</span>
                                        <div className="ml-2 flex -space-x-1">
                                            {note.people.slice(0, 2).map((person, index) => (
                                                <Avatar key={index} className="h-5 w-5 border border-white md:h-6 md:w-6">
                                                    <AvatarImage src={person || '/placeholder.svg'} />
                                                    <AvatarFallback className="text-xs">U</AvatarFallback>
                                                </Avatar>
                                            ))}
                                            {note.people.length > 2 && (
                                                <Avatar className="h-5 w-5 border border-white bg-gray-200 text-gray-600 md:h-6 md:w-6">
                                                    <AvatarFallback className="text-xs">+{note.people.length - 2}</AvatarFallback>
                                                </Avatar>
                                            )}
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-1">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="h-6 w-6 p-0"
                                            onClick={() => setNotes((s) => s.filter((n) => n.id !== note.id))}
                                        >
                                            <Trash2 className="h-3 w-3 text-gray-400 md:h-4 md:w-4" />
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="h-6 w-6 p-0"
                                            onClick={() => setNotes((s) => s.map((n) => (n.id === note.id ? { ...n, favorites: !n.favorites } : n)))}
                                        >
                                            <Heart
                                                className={cn(
                                                    'h-3 w-3 md:h-4 md:w-4',
                                                    note.favorites ? 'fill-red-500 text-red-500' : 'text-gray-400',
                                                )}
                                            />
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Add / Edit Note Modal */}
                <NoteAddModal
                    isAddNoteModalOpen={isAddNoteModalOpen}
                    setIsAddNoteModalOpen={(open) => {
                        setIsAddNoteModalOpen(open);
                        if (!open) {
                            setEditingNote(null);
                            setModalMode('add');
                        }
                    }}
                    mode={modalMode}
                    initialNote={editingNote || undefined}
                    onSubmit={(payload: any) => {
                        if (modalMode === 'add') {
                            const id = String(Date.now());
                            setNotes((s) => [
                                {
                                    id,
                                    title: payload.title || 'Untitled',
                                    description: payload.description || '',
                                    date: payload.date ? new Date(payload.date).toDateString() : new Date().toDateString(),
                                    tag: (payload.tag as any) || 'Personal',
                                    people: [],
                                    bullets: [],
                                    favorites: false,
                                    color: '#60a5fa',
                                },
                                ...s,
                            ]);
                        } else if (modalMode === 'edit' && payload.id) {
                            setNotes((s) =>
                                s.map((n) =>
                                    n.id === payload.id
                                        ? { ...n, ...payload, date: payload.date ? new Date(payload.date).toDateString() : n.date }
                                        : n,
                                ),
                            );
                        }
                    }}
                />
            </div>
        </div>
    );
}
Index.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Tasks', href: '/tasks' },
            { title: 'Tasks', href: route('users.index') },
        ]}
        title="Tasks"
    >
        {page}
    </AppLayout>
);

export default Index;
