import { MobileCard } from "../organisms/MobileCard";
import { SearchFilter } from "../organisms/SearchFilter";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "../ui/pagination";
import { Badge } from "../ui/badge";
import { Edit, Eye, Trash2, Package } from "lucide-react";

export interface MobileItemListItem {
  id: string;
  itemCode: string;
  itemName: string;
  itemType: "FG" | "PT" | "SM" | "RM" | "CS";
  specification?: string;
  unit?: string;
  purchasePrice?: number;
  salesPrice?: number;
  isActive?: boolean;
}

export interface MobileItemListTemplateProps {
  items: MobileItemListItem[];
  searchValue: string;
  onSearchChange: (value: string) => void;
  filterType: string;
  onFilterChange: (value: string) => void;
  currentPage: number;
  onPageChange: (page: number) => void;
  itemsPerPage?: number;
  onItemClick?: (item: MobileItemListItem) => void;
  onEdit?: (item: MobileItemListItem) => void;
  onView?: (item: MobileItemListItem) => void;
  onDelete?: (itemId: string) => void;
  showActions?: boolean;
  canViewPrice?: boolean;
}

const itemTypeLabels: Record<string, string> = {
  FG: "제품",
  PT: "부품",
  SM: "부자재",
  RM: "원자재",
  CS: "소모품",
};

const itemTypeBadgeVariants: Record<string, "default" | "secondary" | "outline" | "destructive"> = {
  FG: "default",
  PT: "secondary",
  SM: "outline",
  RM: "outline",
  CS: "outline",
};

export function MobileItemListTemplate({
  items,
  searchValue,
  onSearchChange,
  filterType,
  onFilterChange,
  currentPage,
  onPageChange,
  itemsPerPage = 20,
  onItemClick,
  onEdit,
  onView,
  onDelete,
  showActions = true,
  canViewPrice = true,
}: MobileItemListTemplateProps) {
  // 필터링된 품목
  const filteredItems = items.filter((item) => {
    const matchesSearch =
      item.itemCode.toLowerCase().includes(searchValue.toLowerCase()) ||
      item.itemName.toLowerCase().includes(searchValue.toLowerCase()) ||
      (item.specification && item.specification.toLowerCase().includes(searchValue.toLowerCase()));

    const matchesType = filterType === "all" || item.itemType === filterType;

    return matchesSearch && matchesType;
  });

  // 페이징 처리
  const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedItems = filteredItems.slice(startIndex, endIndex);

  // 품목 유형별 개수
  const typeCounts = items.reduce((acc, item) => {
    acc[item.itemType] = (acc[item.itemType] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  return (
    <div className="space-y-4">
      {/* 검색 및 필터 */}
      <div className="space-y-3">
        <SearchFilter
          searchValue={searchValue}
          onSearchChange={onSearchChange}
          searchPlaceholder="품목코드, 품목명, 규격 검색..."
          filterButton={false}
        />
        <Select value={filterType} onValueChange={onFilterChange}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="품목 유형" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">전체 ({items.length})</SelectItem>
            <SelectItem value="FG">제품 ({typeCounts.FG || 0})</SelectItem>
            <SelectItem value="PT">부품 ({typeCounts.PT || 0})</SelectItem>
            <SelectItem value="SM">부자재 ({typeCounts.SM || 0})</SelectItem>
            <SelectItem value="RM">원자재 ({typeCounts.RM || 0})</SelectItem>
            <SelectItem value="CS">소모품 ({typeCounts.CS || 0})</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 품목 카드 목록 */}
      <div className="space-y-3">
        {paginatedItems.length === 0 ? (
          <div className="text-center py-12">
            <Package className="w-12 h-12 mx-auto text-muted-foreground mb-3" />
            <p className="text-muted-foreground">품목이 없습니다</p>
          </div>
        ) : (
          paginatedItems.map((item) => {
            const fields = [
              { label: "품목코드", value: item.itemCode },
              { label: "규격", value: item.specification || "-" },
              { label: "단위", value: item.unit || "-" },
            ];

            // 단가 정보 추가 (권한이 있을 경우)
            if (canViewPrice) {
              if (item.purchasePrice !== undefined) {
                fields.push({
                  label: "구매단가",
                  value: `₩${Number(item.purchasePrice).toLocaleString()}`,
                });
              }
              if (item.salesPrice !== undefined) {
                fields.push({
                  label: "판매단가",
                  value: `₩${Number(item.salesPrice).toLocaleString()}`,
                });
              }
            }

            // 활성 상태 추가
            if (item.isActive !== undefined) {
              fields.push({
                label: "상태",
                value: item.isActive ? "활성" : "비활성",
                badge: true,
              });
            }

            const actions = [];

            if (showActions) {
              if (onView) {
                actions.push({
                  label: "상세",
                  icon: Eye,
                  variant: "outline" as const,
                  onClick: () => onView(item),
                });
              }
              if (onEdit) {
                actions.push({
                  label: "수정",
                  icon: Edit,
                  variant: "outline" as const,
                  onClick: () => onEdit(item),
                });
              }
              if (onDelete) {
                actions.push({
                  label: "삭제",
                  icon: Trash2,
                  variant: "outline" as const,
                  onClick: () => onDelete(item.id),
                });
              }
            }

            return (
              <div key={item.id}>
                <MobileCard
                  icon={<Package className="w-5 h-5 text-muted-foreground" />}
                  title={item.itemName}
                  subtitle={itemTypeLabels[item.itemType]}
                  badge={{
                    label: itemTypeLabels[item.itemType],
                    variant: itemTypeBadgeVariants[item.itemType],
                  }}
                  fields={fields}
                  actions={actions.length > 0 ? actions : undefined}
                  onCardClick={onItemClick ? () => onItemClick(item) : undefined}
                />
              </div>
            );
          })
        )}
      </div>

      {/* 페이지네이션 */}
      {totalPages > 1 && (
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                onClick={() => currentPage > 1 && onPageChange(currentPage - 1)}
                className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
              />
            </PaginationItem>
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNumber;
              if (totalPages <= 5) {
                pageNumber = i + 1;
              } else if (currentPage <= 3) {
                pageNumber = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNumber = totalPages - 4 + i;
              } else {
                pageNumber = currentPage - 2 + i;
              }

              return (
                <PaginationItem key={pageNumber}>
                  <PaginationLink
                    onClick={() => onPageChange(pageNumber)}
                    isActive={currentPage === pageNumber}
                    className="cursor-pointer"
                  >
                    {pageNumber}
                  </PaginationLink>
                </PaginationItem>
              );
            })}
            <PaginationItem>
              <PaginationNext
                onClick={() => currentPage < totalPages && onPageChange(currentPage + 1)}
                className={
                  currentPage === totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"
                }
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      )}

      {/* 결과 요약 */}
      <div className="text-center text-sm text-muted-foreground">
        총 {filteredItems.length}개 품목 중 {startIndex + 1}-
        {Math.min(endIndex, filteredItems.length)}개 표시
      </div>
    </div>
  );
}
