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, Upload } from 'lucide-react';
import ProductTable from "@/Components/Product/ProductTable";
import ProductImportDialog from "@/Components/Product/ProductImportDialog";
import CategoryManagerDialog from "@/Components/Category/CategoryManagerDialog";
import UnitManagerDialog, { Unit } from "@/Components/Unit/UnitManagerDialog";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, usePage, Link } from "@inertiajs/react";
import { PageProps as GlobalPageProps } from "@/types/global";
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;
  barcode?: 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;
  location?: string;
  createdAt?: string;
  updatedAt?: string;
  cost_price?: number;
  price?: number;
  member_price?: number;
  wholesale_price?: number;
  is_active?: boolean;
}

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 { branding } = usePage<GlobalPageProps>().props;
  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 [isCategoryDialogOpen, setIsCategoryDialogOpen] = useState(false);
  const [isUnitDialogOpen, setIsUnitDialogOpen] = useState(false);
  const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);

  // 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 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">管理 {branding?.short_name || 'Star'} 原物料與成品資料</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
                  variant="outline"
                  onClick={() => setIsImportDialogOpen(true)}
                  className="flex-1 md:flex-none button-outlined-primary"
                >
                  <Upload className="mr-2 h-4 w-4" />
                  匯入
                </Button>
              </Can>
              <Can permission="products.create">
                <Link href={route("products.create")}>
                  <Button className="w-full md:w-auto button-filled-primary">
                    <Plus className="mr-2 h-4 w-4" />
                    新增商品
                  </Button>
                </Link>
              </Can>
            </div>
          </div>
        </div>

        {/* Product Table */}
        <ProductTable
          products={products.data}
          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-[90px] 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>


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

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

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