import { useState, useEffect, useCallback } from "react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Plus, Search, X, Contact2 } from "lucide-react";
import VendorTable from "@/Components/Vendor/VendorTable";
import VendorDialog from "@/Components/Vendor/VendorDialog";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router } from "@inertiajs/react";
import { debounce } from "lodash";
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { Can } from "@/Components/Permission/Can";
import Pagination from "@/Components/shared/Pagination";
import { SearchableSelect } from "@/Components/ui/searchable-select";

export interface Vendor {
    id: number;
    code: string;
    name: string;
    short_name?: string;
    tax_id?: string;
    owner?: string;
    contact_name?: string;
    tel?: string;
    phone?: string;
    email?: string;
    address?: string;
    remark?: string;
    created_at: string;
    updated_at: string;
}

interface PageProps {
    vendors: {
        data: Vendor[];
        links: any[];
        meta: any;
    };
    filters: {
        search?: string;
        sort_field?: string;
        sort_direction?: string;
        per_page?: string;
    };
}

export default function VendorManagement({ vendors, filters }: PageProps) {
    const [searchTerm, setSearchTerm] = useState(filters.search || "");
    const [sortField, setSortField] = useState<string | null>(filters.sort_field || null);
    const [sortDirection, setSortDirection] = useState<"asc" | "desc" | null>(filters.sort_direction as "asc" | "desc" || null);
    const [perPage, setPerPage] = useState<string>(filters.per_page || "10");
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);

    // Sync state with props
    useEffect(() => {
        setSearchTerm(filters.search || "");
        setSortField(filters.sort_field || null);
        setSortDirection(filters.sort_direction as "asc" | "desc" || null);
        setPerPage(filters.per_page || "10");
    }, [filters]);

    // Debounced Search
    const debouncedSearch = useCallback(
        debounce((term: string) => {
            router.get(
                route("vendors.index"),
                { search: term },
                { preserveState: true, replace: true, preserveScroll: true }
            );
        }, 500),
        []
    );

    const handleSearchChange = (term: string) => {
        setSearchTerm(term);
        debouncedSearch(term);
    };

    const handleClearSearch = () => {
        setSearchTerm("");
        router.get(
            route("vendors.index"),
            { search: "" },
            { preserveState: true, replace: true, preserveScroll: true }
        );
    };

    const handleSort = (field: string) => {
        let newField: string | null = field;
        let newDirection: "asc" | "desc" | null = "asc";

        if (sortField === field) {
            if (sortDirection === "asc") {
                newDirection = "desc";
            } else {
                newDirection = null;
                newField = null;
            }
        }

        setSortField(newField);
        setSortDirection(newDirection);

        router.get(
            route("vendors.index"),
            {
                search: searchTerm,
                sort_field: newField,
                sort_direction: newDirection
            },
            { preserveState: true, replace: true, preserveScroll: true }
        );
    };

    const handleAddVendor = () => {
        setEditingVendor(null);
        setIsDialogOpen(true);
    };

    const handleEditVendor = (vendor: Vendor) => {
        setEditingVendor(vendor);
        setIsDialogOpen(true);
    };

    const handleViewVendor = (vendor: Vendor) => {
        router.get(route("vendors.show", vendor.id));
    };

    const handleDeleteVendor = (id: number) => {
        router.delete(route('vendors.destroy', id));
    };

    const handlePerPageChange = (value: string) => {
        setPerPage(value);
        router.get(
            route("vendors.index"),
            { search: searchTerm, sort_field: sortField, sort_direction: sortDirection, per_page: value },
            { preserveState: false, replace: true, preserveScroll: true }
        );
    };

    return (
        <AuthenticatedLayout breadcrumbs={getBreadcrumbs("vendors")}>
            <Head title="廠商資料管理" />
            <div className="container mx-auto p-6 max-w-7xl">
                {/* Header */}
                <div className="mb-6">
                    <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                        <Contact2 className="h-6 w-6 text-primary-main" />
                        廠商資料管理
                    </h1>
                    <p className="text-gray-500 mt-1">管理 ERP 系統供應商與聯絡資訊</p>
                </div>

                {/* Toolbar */}
                <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="搜尋廠商名稱、編號、統編、負責人..."
                                value={searchTerm}
                                onChange={(e) => handleSearchChange(e.target.value)}
                                className="pl-10 pr-10"
                            />
                            {searchTerm && (
                                <button
                                    onClick={handleClearSearch}
                                    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>

                        {/* Add Button */}
                        <Can permission="vendors.create">
                            <Button onClick={handleAddVendor} className="flex-1 md:flex-none button-filled-primary">
                                <Plus className="mr-2 h-4 w-4" />
                                新增廠商
                            </Button>
                        </Can>
                    </div>
                </div>

                {/* Vendor Table */}
                <VendorTable
                    vendors={vendors.data}
                    onView={handleViewVendor}
                    onEdit={handleEditVendor}
                    onDelete={handleDeleteVendor}
                    sortField={sortField}
                    sortDirection={sortDirection}
                    onSort={handleSort}
                />

                <VendorDialog
                    open={isDialogOpen}
                    onOpenChange={setIsDialogOpen}
                    vendor={editingVendor}
                />

                {/* 分頁元件 - 統一樣式 */}
                <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={vendors.links} />
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
