import { useState } from 'react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, router } from '@inertiajs/react';
import { PageProps } from '@/types/global';
import Pagination from '@/Components/shared/Pagination';
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { FileText, Search, RotateCcw, Calendar } from 'lucide-react';
import LogTable, { Activity } from '@/Components/ActivityLog/LogTable';
import ActivityDetailDialog from '@/Components/ActivityLog/ActivityDetailDialog';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";

interface PaginationLinks {
    url: string | null;
    label: string;
    active: boolean;
}

interface Props extends PageProps {
    activities: {
        data: Activity[];
        links: PaginationLinks[];
        current_page: number;
        last_page: number;
        total: number;
        from: number;
    };
    filters: {
        per_page?: string;
        sort_by?: string;
        sort_order?: 'asc' | 'desc';
        search?: string;
        date_start?: string;
        date_end?: string;
        event?: string;
        subject_type?: string;
        causer_id?: string;
    };
    subject_types: { label: string; value: string }[];
    users: { label: string; value: string }[];
}

export default function ActivityLogIndex({ activities, filters, subject_types, users }: Props) {
    const [perPage, setPerPage] = useState<string>(filters.per_page || "10");
    const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null);
    const [detailOpen, setDetailOpen] = useState(false);

    // Filter States
    const [search, setSearch] = useState(filters.search || '');
    const [dateStart, setDateStart] = useState(filters.date_start || '');
    const [dateEnd, setDateEnd] = useState(filters.date_end || '');
    const [event, setEvent] = useState(filters.event || 'all');
    const [subjectType, setSubjectType] = useState(filters.subject_type || 'all');
    const [causer, setCauser] = useState(filters.causer_id || 'all');

    const handleFilter = () => {
        router.get(
            route('activity-logs.index'),
            {
                ...filters,
                search: search,
                date_start: dateStart,
                date_end: dateEnd,
                event: event === 'all' ? undefined : event,
                subject_type: subjectType === 'all' ? undefined : subjectType,
                causer_id: causer === 'all' ? undefined : causer,
                page: 1 // Reset to first page on filter
            },
            { preserveState: true, replace: true }
        );
    };

    const handleReset = () => {
        setSearch('');
        setDateStart('');
        setDateEnd('');
        setEvent('all');
        setSubjectType('all');
        setCauser('all');

        router.get(
            route('activity-logs.index'),
            { per_page: perPage, sort_by: filters.sort_by, sort_order: filters.sort_order },
            { preserveState: true, replace: true }
        );
    };

    const handleViewDetail = (activity: Activity) => {
        setSelectedActivity(activity);
        setDetailOpen(true);
    };

    const handlePerPageChange = (value: string) => {
        setPerPage(value);
        router.get(
            route('activity-logs.index'),
            { ...filters, per_page: value },
            { preserveState: false, replace: true, preserveScroll: true }
        );
    };

    const handleSort = (field: string) => {
        let newSortBy: string | undefined = field;
        let newSortOrder: 'asc' | 'desc' | undefined = 'asc';

        if (filters.sort_by === field) {
            if (filters.sort_order === 'asc') {
                newSortOrder = 'desc';
            } else {
                newSortBy = undefined;
                newSortOrder = undefined;
            }
        }

        router.get(
            route('activity-logs.index'),
            { ...filters, sort_by: newSortBy, sort_order: newSortOrder },
            { preserveState: true, replace: true }
        );
    };

    return (
        <AuthenticatedLayout
            breadcrumbs={[
                { label: '系統管理', href: '#' },
                { label: '操作紀錄', href: route('activity-logs.index'), isPage: true },
            ]}
        >
            <Head title="操作紀錄" />

            <div className="container mx-auto p-6 max-w-7xl">
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                            <FileText className="h-6 w-6 text-primary-main" />
                            操作紀錄
                        </h1>
                        <p className="text-gray-500 mt-1">
                            檢視系統內的所有操作活動，包含新增、修改與刪除紀錄
                        </p>
                    </div>
                </div>

                {/* 篩選區塊 */}
                <div className="bg-white p-5 rounded-lg shadow-sm border border-gray-200 mb-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
                        {/* 關鍵字搜尋 */}
                        <div className="space-y-1">
                            <Label className="text-xs text-gray-500">關鍵字搜尋</Label>
                            <div className="relative">
                                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
                                <Input
                                    placeholder="搜尋描述、內容..."
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    className="pl-9"
                                    onKeyDown={(e) => e.key === 'Enter' && handleFilter()}
                                />
                            </div>
                        </div>

                        {/* 操作人員 */}
                        <div className="space-y-1">
                            <Label className="text-xs text-gray-500">操作人員</Label>
                            <SearchableSelect
                                value={causer}
                                onValueChange={setCauser}
                                options={[
                                    { label: "所有人員", value: "all" },
                                    ...users
                                ]}
                                placeholder="選擇操作人員"
                                className="w-full"
                            />
                        </div>

                        {/* 事件類型 */}
                        <div className="space-y-1">
                            <Label className="text-xs text-gray-500">事件類型</Label>
                            <Select value={event} onValueChange={setEvent}>
                                <SelectTrigger>
                                    <SelectValue placeholder="選擇事件類型" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">所有事件</SelectItem>
                                    <SelectItem value="created">新增 (Created)</SelectItem>
                                    <SelectItem value="updated">更新 (Updated)</SelectItem>
                                    <SelectItem value="deleted">刪除 (Deleted)</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        {/* 操作對象 */}
                        <div className="space-y-1">
                            <Label className="text-xs text-gray-500">操作對象</Label>
                            <SearchableSelect
                                value={subjectType}
                                onValueChange={setSubjectType}
                                options={[
                                    { label: "所有對象", value: "all" },
                                    ...subject_types
                                ]}
                                placeholder="選擇操作對象"
                                className="w-full"
                            />
                        </div>

                        {/* 日期範圍 - 開始 */}
                        <div className="space-y-1">
                            <Label className="text-xs text-gray-500">開始日期</Label>
                            <div className="relative">
                                <Calendar className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
                                <Input
                                    type="date"
                                    value={dateStart}
                                    onChange={(e) => setDateStart(e.target.value)}
                                    className="pl-9 block w-full"
                                />
                            </div>
                        </div>

                        {/* 日期範圍 - 結束 */}
                        <div className="space-y-1">
                            <Label className="text-xs text-gray-500">結束日期</Label>
                            <div className="relative">
                                <Calendar className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
                                <Input
                                    type="date"
                                    value={dateEnd}
                                    onChange={(e) => setDateEnd(e.target.value)}
                                    className="pl-9 block w-full text-left"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="flex items-center justify-end gap-3 pt-2 border-t border-gray-100">
                        <Button
                            variant="outline"
                            onClick={handleReset}
                            className="flex items-center gap-2 button-outlined-primary"
                        >
                            <RotateCcw className="h-4 w-4" />
                            重置條件
                        </Button>
                        <Button
                            onClick={handleFilter}
                            className="flex items-center gap-2 button-filled-primary"
                        >
                            <Search className="h-4 w-4" />
                            查詢紀錄
                        </Button>
                    </div>
                </div>

                <LogTable
                    activities={activities.data}
                    sortField={filters.sort_by}
                    sortOrder={filters.sort_order}
                    onSort={handleSort}
                    onViewDetail={handleViewDetail}
                    from={activities.from}
                />

                <div className="mt-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div className="flex items-center gap-2 text-sm text-gray-500">
                        <span>每頁顯示</span>
                        <SearchableSelect
                            value={perPage}
                            onValueChange={handlePerPageChange}
                            options={[
                                { label: "10", value: "10" },
                                { label: "20", value: "20" },
                                { label: "50", value: "50" },
                                { label: "100", value: "100" }
                            ]}
                            className="w-[100px] h-8"
                            showSearch={false}
                        />
                        <span>筆</span>
                    </div>
                    <div className="w-full sm:w-auto flex justify-center sm:justify-end">
                        <Pagination links={activities.links} />
                    </div>
                </div>
            </div>

            <ActivityDetailDialog
                open={detailOpen}
                onOpenChange={setDetailOpen}
                activity={selectedActivity}
            />
        </AuthenticatedLayout>
    );
}
