/**
 * 수주관리 - IntegratedListTemplateV2 적용
 * 
 * 견적관리와 동일한 디자인 시스템 템플릿을 적용한 수주 관리 페이지입니다.
 * - PageHeader, StatCards, SearchFilter, 체크박스
 * - 데스크톱: TabsList + DataTable
 * - 모바일: 커스텀 버튼 탭 + 카드 리스트
 * - 완전한 반응형 지원
 */

import { useState, useMemo, useRef, useEffect } from "react";
import { 
  ShoppingCart, Package, CheckCircle, Clock, 
  Edit, Trash2, Eye, FileText, Plus, TrendingUp
} from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Progress } from "./ui/progress";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Checkbox } from "./ui/checkbox";
import { toast } from "sonner@2.0.3";
import { SalesOrderRegistration } from "./SalesOrderRegistration";
import { IntegratedListTemplateV2, TabOption, TableColumn } from "./templates/IntegratedListTemplateV2";
import { StatusBadge } from "./molecules/StatusBadge";
import { ActionButtonGroup } from "./molecules/ActionButtonGroup";
import { ListMobileCard, InfoField } from "./organisms/ListMobileCard";
import { formatAmount, formatAmountManwon } from "../utils/formatAmount";

// 수주 데이터 타입
interface SalesOrderItem {
  id: string;
  orderNo: string;           // 수주번호
  orderLot: string;          // 수주LOT
  orderDate: string;         // 수주일
  buyer: string;             // 발주처
  site: string;              // 현장명
  amount: number;            // 금액
  deliveryDate: string;      // 납기
  status: 'registered' | 'contracted' | 'production_instructed' | 'shipping' | 'completed'; // 상태
  isSplit: boolean;          // 분할여부
  splitCount?: number;       // 분할횟수
  shippedCount: number;      // 출고진행 (출고된 수량)
  totalCount: number;        // 출고진행 (전체 수량)
  paymentStatus: 'pending' | 'partial' | 'completed'; // 입금상태
  taxInvoiceIssued: boolean; // 세금계산서 발행여부
  manager: string;           // 담당자
  creditGrade?: 'A' | 'B' | 'C'; // 신용등급
}

export function SalesOrderManagement() {
  const [viewMode, setViewMode] = useState<'list' | 'register' | 'detail' | 'edit'>('list');
  const [editingOrder, setEditingOrder] = useState<any>(null);
  const [selectedOrder, setSelectedOrder] = useState<SalesOrderItem | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;
  
  // 모바일 인피니티 스크롤 state
  const [mobileDisplayCount, setMobileDisplayCount] = useState(20);
  const sentinelRef = useRef<HTMLDivElement>(null);

  // Mock 데이터
  const [orderData] = useState<SalesOrderItem[]>([
    {
      id: "1",
      orderNo: "SO-2025-001",
      orderLot: "ORD-2025-A001",
      orderDate: "2025-11-15",
      buyer: "한빛에스티",
      site: "반포3지구2공구(117동)",
      amount: 50000000,
      deliveryDate: "2025-12-15",
      status: "contracted",
      isSplit: true,
      splitCount: 3,
      shippedCount: 2,
      totalCount: 3,
      paymentStatus: "partial",
      taxInvoiceIssued: true,
      manager: "김영희",
      creditGrade: "A"
    },
    {
      id: "2",
      orderNo: "SO-2025-002",
      orderLot: "ORD-2025-A002",
      orderDate: "2025-11-20",
      buyer: "주일기업",
      site: "플라이크은평",
      amount: 80000000,
      deliveryDate: "2025-12-20",
      status: "production_instructed",
      isSplit: false,
      shippedCount: 0,
      totalCount: 1,
      paymentStatus: "pending",
      taxInvoiceIssued: false,
      manager: "이철수",
      creditGrade: "B"
    },
    {
      id: "3",
      orderNo: "SO-2025-003",
      orderLot: "ORD-2025-A003",
      orderDate: "2025-11-22",
      buyer: "성지금속",
      site: "한국체대부산경기장",
      amount: 45000000,
      deliveryDate: "2025-12-25",
      status: "registered",
      isSplit: true,
      splitCount: 2,
      shippedCount: 0,
      totalCount: 2,
      paymentStatus: "pending",
      taxInvoiceIssued: false,
      manager: "박민수",
      creditGrade: "C"
    },
    {
      id: "4",
      orderNo: "SO-2025-004",
      orderLot: "ORD-2025-A004",
      orderDate: "2025-11-25",
      buyer: "삼진오토도어",
      site: "강진종합초교(1차)",
      amount: 120000000,
      deliveryDate: "2025-12-30",
      status: "shipping",
      isSplit: true,
      splitCount: 4,
      shippedCount: 3,
      totalCount: 4,
      paymentStatus: "completed",
      taxInvoiceIssued: true,
      manager: "김영희",
      creditGrade: "A"
    },
    {
      id: "5",
      orderNo: "SO-2025-005",
      orderLot: "ORD-2025-A005",
      orderDate: "2025-11-28",
      buyer: "대한건설",
      site: "송도신도시 2단지",
      amount: 95000000,
      deliveryDate: "2026-01-05",
      status: "completed",
      isSplit: false,
      shippedCount: 1,
      totalCount: 1,
      paymentStatus: "completed",
      taxInvoiceIssued: true,
      manager: "이철수",
      creditGrade: "A"
    }
  ]);

  // 필터링 및 정렬
  const filteredOrders = useMemo(() => {
    return orderData
      .filter((order) => {
        const searchLower = searchTerm.toLowerCase();
        const matchesSearch =
          !searchTerm ||
          order.orderNo.toLowerCase().includes(searchLower) ||
          order.buyer.toLowerCase().includes(searchLower) ||
          order.site.toLowerCase().includes(searchLower) ||
          order.orderLot.toLowerCase().includes(searchLower);

        let matchesFilter = true;
        if (filterStatus === "registered") {
          matchesFilter = order.status === "registered";
        } else if (filterStatus === "contracted") {
          matchesFilter = order.status === "contracted";
        } else if (filterStatus === "production_instructed") {
          matchesFilter = order.status === "production_instructed";
        } else if (filterStatus === "shipping") {
          matchesFilter = order.status === "shipping";
        } else if (filterStatus === "completed") {
          matchesFilter = order.status === "completed";
        } else if (filterStatus === "in_progress") {
          matchesFilter = ["registered", "contracted", "production_instructed", "shipping"].includes(order.status);
        }

        return matchesSearch && matchesFilter;
      })
      .sort((a, b) => {
        return new Date(b.orderDate).getTime() - new Date(a.orderDate).getTime();
      });
  }, [orderData, searchTerm, filterStatus]);

  // 페이지네이션
  const totalPages = Math.ceil(filteredOrders.length / itemsPerPage);
  const paginatedOrders = filteredOrders.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // 모바일용 인피니티 스크롤 데이터
  const mobileOrders = filteredOrders.slice(0, mobileDisplayCount);

  // Intersection Observer를 이용한 인피니티 스크롤
  useEffect(() => {
    if (window.innerWidth >= 1280) return;
    
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && mobileDisplayCount < filteredOrders.length) {
          setMobileDisplayCount(prev => Math.min(prev + 20, filteredOrders.length));
        }
      },
      {
        threshold: 0.1,
        rootMargin: '100px',
      }
    );
    
    if (sentinelRef.current) {
      observer.observe(sentinelRef.current);
    }
    
    return () => {
      observer.disconnect();
    };
  }, [mobileDisplayCount, filteredOrders.length]);

  // 탭이나 검색어 변경 시 모바일 표시 개수 초기화
  useEffect(() => {
    setMobileDisplayCount(20);
  }, [searchTerm, filterStatus]);

  // 대시보드 통계
  const stats = useMemo(() => {
    const totalOrders = orderData.length;
    const inProgress = orderData.filter(o => 
      ["registered", "contracted", "production_instructed", "shipping"].includes(o.status)
    ).length;
    const completed = orderData.filter(o => o.status === "completed").length;
    const splitOrders = orderData.filter(o => o.isSplit).length;
    const totalAmount = orderData.reduce((sum, o) => sum + o.amount, 0);

    return [
      {
        label: "전체 수주",
        value: `${totalOrders}건`,
        icon: ShoppingCart,
        iconColor: "text-blue-600",
      },
      {
        label: "진행중",
        value: `${inProgress}건`,
        icon: Clock,
        iconColor: "text-orange-600",
      },
      {
        label: "완료",
        value: `${completed}건`,
        icon: CheckCircle,
        iconColor: "text-green-600",
      },
      {
        label: "총 수주 금액",
        value: formatAmountManwon(totalAmount),
        icon: TrendingUp,
        iconColor: "text-purple-600",
      },
    ];
  }, [orderData]);

  // 핸들러
  const handleView = (order: SalesOrderItem) => {
    setSelectedOrder(order);
    setViewMode("detail");
  };

  const handleEdit = (order: SalesOrderItem) => {
    setEditingOrder(order);
    setViewMode("edit");
  };

  const handleDelete = (orderId: string) => {
    if (confirm("이 수주를 삭제하시겠습니까?")) {
      toast.success("수주가 삭제되었습니다");
    }
  };

  // 체크박스 선택
  const toggleSelection = (id: string) => {
    const newSelection = new Set(selectedItems);
    if (newSelection.has(id)) {
      newSelection.delete(id);
    } else {
      newSelection.add(id);
    }
    setSelectedItems(newSelection);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === paginatedOrders.length && paginatedOrders.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedOrders.map((o) => o.id)));
    }
  };

  // 일괄 삭제
  const handleBulkDelete = () => {
    if (selectedItems.size === 0) {
      toast.error("삭제할 항목을 선택해주세요");
      return;
    }
    
    if (confirm(`선택한 ${selectedItems.size}개의 수주를 삭제하시겠습니까?`)) {
      toast.success(`${selectedItems.size}개의 수주가 삭제되었습니다`);
      setSelectedItems(new Set());
    }
  };

  // 상태 뱃지
  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { label: string; variant: any }> = {
      registered: { label: "수주등록", variant: "default" },
      contracted: { label: "수주계약완료", variant: "info" },
      production_instructed: { label: "생산지시완료", variant: "secondary" },
      shipping: { label: "출하중", variant: "warning" },
      completed: { label: "완료", variant: "success" }
    };
    const config = statusMap[status] || statusMap.registered;
    return <StatusBadge label={config.label} variant={config.variant} />;
  };

  const getPaymentBadge = (status: string) => {
    const statusMap: Record<string, { label: string; variant: any }> = {
      pending: { label: "미입금", variant: "danger" },
      partial: { label: "부분입금", variant: "warning" },
      completed: { label: "입금완료", variant: "success" }
    };
    const config = statusMap[status] || statusMap.pending;
    return <StatusBadge label={config.label} variant={config.variant} />;
  };

  // 출고진행율 계산
  const getShippingProgress = (shippedCount: number, totalCount: number) => {
    return totalCount > 0 ? Math.round((shippedCount / totalCount) * 100) : 0;
  };

  // 탭 구성
  const tabs: TabOption[] = [
    {
      value: "all",
      label: "전체",
      count: orderData.length,
      color: "blue",
    },
    {
      value: "in_progress",
      label: "진행중",
      count: orderData.filter((o) => 
        ["registered", "contracted", "production_instructed", "shipping"].includes(o.status)
      ).length,
      color: "orange",
    },
    {
      value: "registered",
      label: "수주등록",
      count: orderData.filter((o) => o.status === "registered").length,
      color: "gray",
    },
    {
      value: "contracted",
      label: "계약완료",
      count: orderData.filter((o) => o.status === "contracted").length,
      color: "blue",
    },
    {
      value: "production_instructed",
      label: "생산지시",
      count: orderData.filter((o) => o.status === "production_instructed").length,
      color: "purple",
    },
    {
      value: "shipping",
      label: "출하중",
      count: orderData.filter((o) => o.status === "shipping").length,
      color: "orange",
    },
    {
      value: "completed",
      label: "완료",
      count: orderData.filter((o) => o.status === "completed").length,
      color: "green",
    },
  ];

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = [
    { key: "rowNumber", label: "번호", className: "px-4" },
    { key: "orderNo", label: "수주번호", className: "px-4" },
    { key: "orderLot", label: "수주LOT", className: "px-4" },
    { key: "orderDate", label: "수주일", className: "px-4" },
    { key: "buyer", label: "발주처", className: "px-4" },
    { key: "site", label: "현장명", className: "px-4" },
    { key: "amount", label: "금액", className: "px-4" },
    { key: "deliveryDate", label: "납기", className: "px-4" },
    { key: "status", label: "상태", className: "px-4" },
    { key: "payment", label: "입금상태", className: "px-4" },
    { key: "shipping", label: "출고진행", className: "px-4" },
    { key: "manager", label: "담당자", className: "px-4" },
    { key: "actions", label: "작업", className: "px-4" },
  ];

  // 테이블 행 렌더링
  const renderTableRow = (order: SalesOrderItem, index: number, globalIndex: number) => {
    const itemId = order.id;
    const isSelected = selectedItems.has(itemId);
    const shippingProgress = getShippingProgress(order.shippedCount, order.totalCount);

    return (
      <TableRow 
        key={order.id} 
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? "bg-blue-50" : ""}`}
        onClick={() => handleView(order)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => toggleSelection(itemId)}
          />
        </TableCell>
        <TableCell>{globalIndex}</TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
            {order.orderNo}
          </code>
        </TableCell>
        <TableCell>
          <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
            {order.orderLot}
          </code>
        </TableCell>
        <TableCell>{order.orderDate}</TableCell>
        <TableCell>{order.buyer}</TableCell>
        <TableCell>{order.site}</TableCell>
        <TableCell className="text-right">{formatAmount(order.amount)}</TableCell>
        <TableCell>{order.deliveryDate}</TableCell>
        <TableCell>{getStatusBadge(order.status)}</TableCell>
        <TableCell>{getPaymentBadge(order.paymentStatus)}</TableCell>
        <TableCell>
          <div className="flex flex-col gap-1">
            <div className="flex items-center gap-2">
              <Progress value={shippingProgress} className="h-2 flex-1" />
              <span className="text-xs text-muted-foreground whitespace-nowrap">
                {order.shippedCount}/{order.totalCount}
              </span>
            </div>
          </div>
        </TableCell>
        <TableCell>{order.manager}</TableCell>
        <TableCell onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <div className="flex gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(order)}
              >
                <Edit className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleDelete(order.id)}
              >
                <Trash2 className="h-4 w-4 text-red-500" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (order: SalesOrderItem, index: number, globalIndex: number, isSelected: boolean, onToggle: () => void) => {
    const shippingProgress = getShippingProgress(order.shippedCount, order.totalCount);
    
    return (
      <ListMobileCard
        key={order.id}
        id={order.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleView(order)}
        headerBadges={
          <>
            <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
              #{globalIndex}
            </Badge>
            <code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono whitespace-nowrap">
              {order.orderNo}
            </code>
          </>
        }
        title={order.buyer}
        statusBadge={getStatusBadge(order.status)}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="현장명" value={order.site} />
            <InfoField 
              label="수주LOT" 
              value={
                <code className="inline-block text-xs bg-blue-50 text-blue-700 px-1.5 py-0.5 rounded font-mono">
                  {order.orderLot}
                </code>
              } 
            />
            <InfoField label="수주일" value={order.orderDate} />
            <InfoField label="납기" value={order.deliveryDate} />
            <InfoField label="담당자" value={order.manager} />
            <InfoField 
              label="입금상태" 
              value={getPaymentBadge(order.paymentStatus)} 
            />
            <InfoField 
              label="총 금액" 
              value={formatAmount(order.amount)} 
              valueClassName="text-green-600" 
            />
            <InfoField 
              label="출고진행"
              value={
                <div className="flex flex-col gap-1">
                  <Progress value={shippingProgress} className="h-2" />
                  <span className="text-xs text-muted-foreground">
                    {order.shippedCount}/{order.totalCount} ({shippingProgress}%)
                  </span>
                </div>
              }
            />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(order);
                }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-[rgba(255,255,255,0)]"
                onClick={(e) => {
                  e.stopPropagation();
                  handleDelete(order.id);
                }}
              >
                <Trash2 className="h-4 w-4 mr-2" />
                삭제
              </Button>
            </div>
          ) : undefined
        }
      />
    );
  };

  // 수주 등록/수정 화면 표시
  if (viewMode === "register" || viewMode === "edit") {
    return (
      <div className="space-y-4">
        <SalesOrderRegistration
          editingOrder={editingOrder}
          onSave={(data) => {
            console.log('Saving order:', data);
            setViewMode('list');
            setEditingOrder(null);
            toast.success(viewMode === "edit" ? "수주가 수정되었습니다" : "수주가 등록되었습니다");
          }}
          onCancel={() => {
            setViewMode('list');
            setEditingOrder(null);
          }}
        />
      </div>
    );
  }

  // 수주 상세 보기 화면
  if (viewMode === "detail" && selectedOrder) {
    return (
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Button 
            variant="outline" 
            size="sm"
            onClick={() => {
              setViewMode("list");
              setSelectedOrder(null);
            }}
          >
            <Eye className="h-4 w-4 mr-2" />
            목록으로
          </Button>
        </div>
        
        <div className="bg-white p-6 rounded-lg border">
          <h2 className="text-xl font-bold mb-4">수주 상세</h2>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            <InfoField label="수주번호" value={selectedOrder.orderNo} />
            <InfoField label="수주LOT" value={selectedOrder.orderLot} />
            <InfoField label="발주처" value={selectedOrder.buyer} />
            <InfoField label="현장명" value={selectedOrder.site} />
            <InfoField label="수주일" value={selectedOrder.orderDate} />
            <InfoField label="납기" value={selectedOrder.deliveryDate} />
            <InfoField label="담당자" value={selectedOrder.manager} />
            <InfoField label="금액" value={formatAmount(selectedOrder.amount)} valueClassName="text-green-600" />
          </div>
          
          <div className="mt-6 flex gap-2">
            <Button onClick={() => {
              setEditingOrder(selectedOrder);
              setViewMode("edit");
            }}>
              <Edit className="h-4 w-4 mr-2" />
              수정
            </Button>
          </div>
        </div>
      </div>
    );
  }

  // 목록 화면 - IntegratedListTemplateV2 사용
  return (
    <IntegratedListTemplateV2
      title="수주 목록"
      description="수주 목록 및 진행현황 조회"
      icon={ShoppingCart}
      headerActions={
        <>
          <Button 
            variant="outline"
            onClick={() => toast.info("견적 불러오기 기능")}
          >
            <FileText className="w-4 h-4 mr-2" />
            견적불러오기
          </Button>
          <Button onClick={() => {
            setEditingOrder(null);
            setViewMode("register");
          }}>
            <Plus className="w-4 h-4 mr-2" />
            신규 수주
          </Button>
        </>
      }
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="수주번호, 발주처, 현장명, 수주LOT 검색..."
      tabs={tabs}
      activeTab={filterStatus}
      onTabChange={(value) => {
        setFilterStatus(value);
        setCurrentPage(1);
      }}
      tableColumns={tableColumns}
      tableTitle={`${tabs.find(t => t.value === filterStatus)?.label || "전체"} (${filteredOrders.length}개)`}
      data={paginatedOrders}
      totalCount={filteredOrders.length}
      allData={mobileOrders}
      mobileDisplayCount={mobileDisplayCount}
      infinityScrollSentinelRef={sentinelRef}
      selectedItems={selectedItems}
      onToggleSelection={toggleSelection}
      onToggleSelectAll={toggleSelectAll}
      onBulkDelete={handleBulkDelete}
      getItemId={(order) => order.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={{
        currentPage,
        totalPages,
        totalItems: filteredOrders.length,
        itemsPerPage,
        onPageChange: setCurrentPage,
      }}
    />
  );
}
