import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link } from '@inertiajs/react';
import { Button } from '@/Components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/Components/ui/table';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";
import { Badge } from "@/Components/ui/badge";
import { Plus, FileUp, Eye, Trash2, Search, X } from 'lucide-react';
import { useState, useEffect } from "react";
import { format } from 'date-fns';
import Pagination from "@/Components/shared/Pagination";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { router } from "@inertiajs/react";
import { usePermission } from "@/hooks/usePermission";
import SalesImportDialog from "@/Components/Sales/SalesImportDialog";

interface ImportBatch {
    id: number;
    import_date: string;
    status: 'pending' | 'confirmed';
    total_quantity: number;
    total_amount: number;
    importer?: {
        name: string;
    };
    created_at: string;
}

interface Props {
    batches: {
        data: ImportBatch[];
        links: any[]; // Pagination links
    };
    filters?: {
        per_page?: string;
        search?: string;
    }
}

export default function SalesImportIndex({ batches, filters = {} }: Props) {
    const { can } = usePermission();
    const [perPage, setPerPage] = useState(filters?.per_page?.toString() || "10");
    const [search, setSearch] = useState(filters?.search || "");
    const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);

    useEffect(() => {
        if (filters?.per_page) {
            setPerPage(filters.per_page.toString());
        }
        setSearch(filters?.search || "");
    }, [filters]);

    const handleFilter = () => {
        router.get(
            route("sales-imports.index"),
            {
                per_page: perPage,
                search: search
            },
            { preserveState: true, replace: true }
        );
    };

    const handlePerPageChange = (value: string) => {
        setPerPage(value);
        router.get(
            route("sales-imports.index"),
            { ...filters, per_page: value },
            { preserveState: true, preserveScroll: true, replace: true }
        );
    };

    return (
        <AuthenticatedLayout
            breadcrumbs={[
                { label: '銷售管理', href: '#' },
                { label: '銷售單匯入', href: route('sales-imports.index'), isPage: true },
            ]}
        >
            <Head title="銷售單匯入管理" />

            <div className="container mx-auto p-6 max-w-7xl">
                <div className="flex justify-between items-center mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                            <FileUp className="h-6 w-6 text-primary-main" />
                            銷售單匯入管理
                        </h1>
                        <p className="text-gray-500 mt-1">
                            匯入並管理銷售出貨紀錄
                        </p>
                    </div>
                </div>

                {/* Toolbar (Aligned with Recipe Management) */}
                <div className="bg-white rounded-lg shadow-sm border p-4 mb-6">
                    <div className="flex flex-col md:flex-row gap-4">
                        {/* Search */}
                        <div className="flex-1 relative">
                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                            <Input
                                placeholder="搜尋批次 ID、匯入人員..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                className="pl-10 pr-10 h-9"
                                onKeyDown={(e) => e.key === 'Enter' && handleFilter()}
                            />
                            {search && (
                                <button
                                    onClick={() => {
                                        setSearch("");
                                        router.get(route('sales-imports.index'), { ...filters, search: "" }, { preserveState: true, replace: true });
                                    }}
                                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                >
                                    <X className="h-4 w-4" />
                                </button>
                            )}
                        </div>

                        {/* Action Buttons */}
                        <div className="flex gap-2 w-full md:w-auto">
                            <Button
                                variant="outline"
                                className="button-outlined-primary"
                                onClick={handleFilter}
                            >
                                <Search className="w-4 h-4 mr-2" />
                                搜尋
                            </Button>

                            {can('sales_imports.create') && (
                                <Button
                                    className="button-filled-primary gap-2"
                                    onClick={() => setIsImportDialogOpen(true)}
                                >
                                    <Plus className="h-4 w-4" />
                                    新增匯入
                                </Button>
                            )}
                        </div>
                    </div>
                </div>

                <SalesImportDialog
                    open={isImportDialogOpen}
                    onOpenChange={setIsImportDialogOpen}
                />

                <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
                    <Table>
                        <TableHeader className="bg-gray-50">
                            <TableRow>
                                <TableHead className="w-[80px] text-center">#</TableHead>
                                <TableHead>匯入日期</TableHead>
                                <TableHead>匯入人員</TableHead>
                                <TableHead className="text-center w-[120px]">總數量</TableHead>
                                <TableHead className="text-right w-[150px]">總金額</TableHead>
                                <TableHead className="text-center w-[100px]">狀態</TableHead>
                                <TableHead className="text-center w-[120px]">操作</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {batches.data.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                                        尚無匯入紀錄
                                    </TableCell>
                                </TableRow>
                            ) : (
                                batches.data.map((batch, index) => (
                                    <TableRow key={batch.id} className="hover:bg-gray-50/50">
                                        <TableCell className="text-center text-gray-500">
                                            {(batches as any).from + index}
                                        </TableCell>
                                        <TableCell>
                                            {format(new Date(batch.created_at), 'yyyy/MM/dd HH:mm')}
                                        </TableCell>
                                        <TableCell>{batch.importer?.name || '--'}</TableCell>
                                        <TableCell className="text-center font-bold text-gray-900">
                                            {Math.floor(batch.total_quantity || 0).toLocaleString()}
                                        </TableCell>
                                        <TableCell className="text-right font-bold text-primary-main">
                                            NT$ {Number(batch.total_amount || 0).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })}
                                        </TableCell>
                                        <TableCell className="text-center">
                                            <Badge variant={batch.status === 'confirmed' ? 'default' : 'secondary'}>
                                                {batch.status === 'confirmed' ? '已確認' : '待確認'}
                                            </Badge>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex justify-center gap-2">
                                                <Link href={route('sales-imports.show', batch.id)}>
                                                    <Button variant="outline" size="sm" className="button-outlined-primary" title="查看詳情">
                                                        <Eye className="h-4 w-4" />
                                                    </Button>
                                                </Link>
                                                {batch.status === 'pending' && can('sales_imports.delete') && (
                                                    <AlertDialog>
                                                        <AlertDialogTrigger asChild>
                                                            <Button variant="outline" size="sm" className="button-outlined-error" title="刪除">
                                                                <Trash2 className="h-4 w-4" />
                                                            </Button>
                                                        </AlertDialogTrigger>
                                                        <AlertDialogContent>
                                                            <AlertDialogHeader>
                                                                <AlertDialogTitle>確認刪除匯入紀錄</AlertDialogTitle>
                                                                <AlertDialogDescription>
                                                                    確定要刪除此筆匯入紀錄（#{batch.id}）嗎？此操作將會移除所有相關的明細資料且無法復原。
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel>取消</AlertDialogCancel>
                                                                <AlertDialogAction
                                                                    className="bg-red-600 hover:bg-red-700"
                                                                    onClick={() => router.delete(route('sales-imports.destroy', batch.id), { preserveScroll: true })}
                                                                >
                                                                    確認刪除
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                )}
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </div>

                {/* Pagination */}
                <div className="mt-4 flex flex-col sm:flex-row 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>
                    <Pagination links={batches.links} />
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
