/**
 * 採購退回單管理主頁面
 */

import { useState, useEffect } from "react";
import { Plus, Package, Search, RotateCcw } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router } from "@inertiajs/react";
import PurchaseReturnTable from "@/Components/PurchaseReturn/PurchaseReturnTable";
import type { PurchaseReturn } from "@/types/purchase-return";
import Pagination from "@/Components/shared/Pagination";
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { Can } from "@/Components/Permission/Can";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";
import { PURCHASE_RETURN_STATUS_CONFIG } from "@/types/purchase-return";

interface Props {
    purchaseReturns: {
        data: PurchaseReturn[];
        links: any[];
        total: number;
        from: number;
        to: number;
    };
    filters: {
        search?: string;
        status?: string;
        per_page?: string;
    };
}

export default function PurchaseReturnIndex({ purchaseReturns, filters }: Props) {
    const [search, setSearch] = useState(filters.search || "");
    const [status, setStatus] = useState<string>(filters.status || "all");
    const [perPage, setPerPage] = useState<string>(filters.per_page || "15");

    // 同步 URL 參數
    useEffect(() => {
        setSearch(filters.search || "");
        setStatus(filters.status || "all");
        setPerPage(filters.per_page || "15");
    }, [filters]);

    const handleFilter = () => {
        router.get(
            route('purchase-returns.index'),
            {
                search,
                status: status === 'all' ? undefined : status,
                per_page: perPage,
            },
            { preserveState: true, replace: true }
        );
    };

    const handleReset = () => {
        setSearch("");
        setStatus("all");
        setPerPage("15");
        router.get(route('purchase-returns.index'));
    };

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

    const handleNavigateToCreate = () => {
        router.get(route('purchase-returns.create'));
    };

    const statusOptions = Object.entries(PURCHASE_RETURN_STATUS_CONFIG).map(([key, config]) => ({
        value: key,
        label: config.label
    }));

    return (
        // TODO: 加入 Breadcrumbs 對應到 purchaseReturns (如果目前 getBreadcrumbs 尚未支援，可先傳入自訂或加入 utils 支援)
        <AuthenticatedLayout breadcrumbs={getBreadcrumbs("purchaseReturns")}>
            <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">
                            <Package className="h-6 w-6 text-primary-main" />
                            採購退回單管理
                        </h1>
                        <p className="text-gray-500 mt-1">
                            管理退回給供應商的商品紀錄與庫存扣減
                        </p>
                    </div>
                    <div className="flex gap-2">
                        <Can permission="purchase_returns.create">
                            <Button
                                onClick={handleNavigateToCreate}
                                className="gap-2 button-filled-primary"
                            >
                                <Plus className="h-4 w-4" />
                                建立退回單
                            </Button>
                        </Can>
                    </div>
                </div>

                {/* 篩選區塊 */}
                <div className="bg-white rounded-xl shadow-sm border border-grey-4 p-5 mb-6">
                    <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-end">
                        {/* Search */}
                        <div className="md:col-span-5 space-y-1">
                            <Label className="text-xs font-medium text-grey-1">關鍵字搜尋</Label>
                            <div className="relative">
                                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                                <Input
                                    placeholder="搜尋退回單號、廠商名稱..."
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    className="pl-10 h-9 block"
                                    onKeyDown={(e) => e.key === 'Enter' && handleFilter()}
                                />
                            </div>
                        </div>

                        {/* Status */}
                        <div className="md:col-span-3 space-y-1">
                            <Label className="text-xs font-medium text-grey-1">訂單狀態</Label>
                            <Select value={status} onValueChange={setStatus}>
                                <SelectTrigger className="h-9">
                                    <SelectValue placeholder="選擇狀態" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">全部狀態</SelectItem>
                                    {statusOptions.map((option) => (
                                        <SelectItem key={option.value} value={option.value}>
                                            {option.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Actions */}
                        <div className="md:col-span-4 flex items-center justify-end gap-2">
                            <Button
                                variant="outline"
                                onClick={handleReset}
                                className="flex-1 flex items-center justify-center gap-2 button-outlined-primary h-9"
                            >
                                <RotateCcw className="h-4 w-4" />
                                重置
                            </Button>
                            <Button
                                onClick={handleFilter}
                                className="flex-1 flex items-center justify-center gap-2 button-filled-primary h-9"
                            >
                                <Search className="h-4 w-4" />
                                查詢
                            </Button>
                        </div>
                    </div>
                </div>

                <PurchaseReturnTable
                    purchaseReturns={purchaseReturns.data}
                />

                {/* 分頁元件 */}
                <div className="mt-6 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <div className="flex items-center 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>
                        <span className="text-sm text-gray-500">共 {purchaseReturns.total} 筆資料</span>
                    </div>
                    <div className="w-full sm:w-auto flex justify-center sm:justify-end">
                        <Pagination links={purchaseReturns.links} />
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
