import { useState, useEffect, useCallback } from "react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Plus, Search, Package, X } from 'lucide-react';
import ProductTable from "@/Components/Product/ProductTable";
import ProductDialog from "@/Components/Product/ProductDialog";
import CategoryManagerDialog from "@/Components/Category/CategoryManagerDialog";
import UnitManagerDialog, { Unit } from "@/Components/Unit/UnitManagerDialog";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router } from "@inertiajs/react";
import { debounce } from "lodash";
import Pagination from "@/Components/shared/Pagination";
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { Can } from "@/Components/Permission/Can";

export interface Category {
  id: number;
  name: string;
}

export interface Product {
  id: string;
  code: string;
  name: string;
  categoryId: number;
  category?: Category;
  brand?: string;
  specification?: string;
  baseUnitId: number;
  baseUnit?: Unit;
  largeUnitId?: number;
  largeUnit?: Unit;
  conversionRate?: number;
  purchaseUnitId?: number;
  purchaseUnit?: Unit;
  createdAt?: string;
  updatedAt?: string;
}

interface PageProps {
  products: {
    data: Product[];
    links: any[]; // Todo: pagination types
    from: number;
  };
  categories: Category[];
  units: Unit[];
  filters: {
    search?: string;
    category_id?: string;
    per_page?: string;
    sort_field?: string;
    sort_direction?: string;
  };
}

export default function ProductManagement({ products, categories, units, filters }: PageProps) {
  const [searchTerm, setSearchTerm] = useState(filters.search || "");
  const [typeFilter, setTypeFilter] = useState<string>(filters.category_id || "all");
  const [perPage, setPerPage] = useState<string>(filters.per_page || "10");
  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 [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isCategoryDialogOpen, setIsCategoryDialogOpen] = useState(false);
  const [isUnitDialogOpen, setIsUnitDialogOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  // Sync state with props when they change (e.g. navigation)
  useEffect(() => {
    setSearchTerm(filters.search || "");
    setTypeFilter(filters.category_id || "all");
    setSearchTerm(filters.search || "");
    setTypeFilter(filters.category_id || "all");
    setPerPage(filters.per_page || "10");
    setSortField(filters.sort_field || null);
    setSortDirection(filters.sort_direction as "asc" | "desc" || null);
  }, [filters]);

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

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

    setSortField(newField);
    setSortDirection(newDirection);

    router.get(
      route("products.index"),
      {
        search: searchTerm,
        category_id: typeFilter,
        per_page: perPage,
        sort_field: newField,
        sort_direction: newDirection
      },
      { preserveState: true, replace: true, preserveScroll: true }
    );
  };

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

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

  const handleCategoryChange = (value: string) => {
    setTypeFilter(value);
    // Immediate update for category
    router.get(
      route("products.index"),
      { search: searchTerm, category_id: value },
      { preserveState: false, replace: true, preserveScroll: true }
    );
  };

  const handleClearSearch = () => {
    setSearchTerm("");
    // Immediate update for clear
    router.get(
      route("products.index"),
      { search: "", category_id: typeFilter, per_page: perPage },
      { preserveState: true, replace: true, preserveScroll: true }
    );
  };

  const handlePerPageChange = (value: string) => {
    setPerPage(value);
    router.get(
      route("products.index"),
      { search: searchTerm, category_id: typeFilter, per_page: value },
      { preserveState: false, replace: true, preserveScroll: true }
    );
  };

  const handleAddProduct = () => {
    setEditingProduct(null);
    setIsDialogOpen(true);
  };

  const handleEditProduct = (product: Product) => {
    setEditingProduct(product);
    setIsDialogOpen(true);
  };

  const handleDeleteProduct = (id: string) => {
    router.delete(route('products.destroy', id), {
      onSuccess: () => {
        // Toast handled by flash message
      }
    });
  };

  return (
    <AuthenticatedLayout breadcrumbs={getBreadcrumbs("products")}>
      <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">
            <Package className="h-6 w-6 text-primary-main" />
            商品資料管理
          </h1>
          <p className="text-gray-500 mt-1">管理小小冰室原物料與成品資料</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>

            {/* Type Filter */}
            <SearchableSelect
              value={typeFilter}
              onValueChange={handleCategoryChange}
              options={[
                { label: "全部分類", value: "all" },
                ...categories.map((cat) => ({ label: cat.name, value: cat.id.toString() }))
              ]}
              placeholder="商品分類"
              className="w-full md:w-[180px]"
            />

            {/* Action Buttons */}
            <div className="flex gap-2 w-full md:w-auto">
              <Can permission="products.edit">
                <Button
                  variant="outline"
                  onClick={() => setIsCategoryDialogOpen(true)}
                  className="flex-1 md:flex-none button-outlined-primary"
                >
                  管理分類
                </Button>
              </Can>
              <Can permission="products.edit">
                <Button
                  variant="outline"
                  onClick={() => setIsUnitDialogOpen(true)}
                  className="flex-1 md:flex-none button-outlined-primary"
                >
                  管理單位
                </Button>
              </Can>
              <Can permission="products.create">
                <Button onClick={handleAddProduct} className="flex-1 md:flex-none button-filled-primary">
                  <Plus className="mr-2 h-4 w-4" />
                  新增商品
                </Button>
              </Can>
            </div>
          </div>
        </div>

        {/* Product Table */}
        <ProductTable
          products={products.data}
          onEdit={handleEditProduct}
          onDelete={handleDeleteProduct}
          startIndex={products.from}
          sortField={sortField}
          sortDirection={sortDirection}
          onSort={handleSort}
        />

        {/* 分頁元件 */}
        <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={products.links} />
          </div>
        </div>

        <ProductDialog
          open={isDialogOpen}
          onOpenChange={setIsDialogOpen}
          product={editingProduct}
          categories={categories}
          units={units}
        />

        <CategoryManagerDialog
          open={isCategoryDialogOpen}
          onOpenChange={setIsCategoryDialogOpen}
          categories={categories}
        />

        <UnitManagerDialog
          open={isUnitDialogOpen}
          onOpenChange={setIsUnitDialogOpen}
          units={units}
        />
      </div>
    </AuthenticatedLayout>
  );
}