/**
 * 견적 푸터 바
 *
 * - 예상 전체 견적금액 표시
 * - 버튼: 견적서 보기, 거래명세서 보기, 할인하기, 최종확정
 * - 뒤로가기 버튼
 */

"use client";

import { Save, Check, X, ArrowLeft, Loader2, FileText, Pencil, ClipboardList, Percent, Calculator } from "lucide-react";

import { Button } from "../ui/button";
import { formatNumber } from "@/lib/utils/amount";
import { useMenuStore } from "@/stores/menuStore";

// =============================================================================
// Props
// =============================================================================

interface QuoteFooterBarProps {
  totalLocations: number;
  totalAmount: number;
  status: "draft" | "temporary" | "final" | "converted";
  /** 견적서 보기 */
  onQuoteView: () => void;
  /** 거래명세서 보기 */
  onTransactionView: () => void;
  /** 저장 (임시저장) */
  onSave: () => void;
  /** 최종확정 */
  onFinalize: () => void;
  /** 뒤로가기 (목록으로) */
  onBack: () => void;
  /** 취소 (목록으로 이동) */
  onCancel?: () => void;
  /** 수정 */
  onEdit?: () => void;
  /** 수주등록 */
  onOrderRegister?: () => void;
  /** 수주 보기 (이미 수주가 있는 경우) */
  onOrderView?: () => void;
  /** 연결된 수주 ID (있으면 수주 보기, 없으면 수주등록) */
  orderId?: number | null;
  /** 수정 가능 여부 (생산지시 존재 시 false) */
  isEditable?: boolean;
  /** 연결된 수주에 생산지시 존재 여부 */
  hasWorkOrders?: boolean;
  /** 할인하기 */
  onDiscount?: () => void;
  /** 수식보기 */
  onFormulaView?: () => void;
  /** BOM 결과 유무 */
  hasBomResult?: boolean;
  isSaving?: boolean;
  disabled?: boolean;
  /** view 모드 여부 (view: 수정+최종확정, edit: 저장+최종확정) */
  isViewMode?: boolean;
}

// =============================================================================
// 컴포넌트
// =============================================================================

export function QuoteFooterBar({
  totalLocations,
  totalAmount,
  status,
  onQuoteView,
  onTransactionView,
  onSave,
  onFinalize,
  onBack,
  onCancel,
  onEdit,
  onOrderRegister,
  onOrderView,
  orderId,
  isEditable = true,
  hasWorkOrders = false,
  onDiscount,
  onFormulaView,
  hasBomResult = false,
  isSaving = false,
  disabled: _disabled = false,
  isViewMode = false,
}: QuoteFooterBarProps) {
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  return (
    <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[24px] ${sidebarCollapsed ? 'md:left-[120px]' : 'md:left-[280px]'}`}>
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0">
        {/* 왼쪽: 취소 + 목록으로 */}
        <div className="flex items-center gap-2">
          {!isViewMode && onCancel && (
            <Button
              variant="outline"
              onClick={onCancel}
              size="sm"
              className="md:size-default shrink-0"
            >
              <X className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">취소</span>
            </Button>
          )}
          {isViewMode && (
            <Button
              variant="outline"
              onClick={onBack}
              size="sm"
              className="md:size-default shrink-0"
            >
              <ArrowLeft className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">목록으로</span>
            </Button>
          )}
        </div>

        {/* 오른쪽: 버튼들 */}
        <div className="flex items-center flex-wrap gap-1 md:gap-3 justify-end">
          {/* 견적서 보기 */}
          <Button
            onClick={onQuoteView}
            disabled={totalLocations === 0}
            variant="outline"
            size="sm"
            className="md:size-default md:px-6"
          >
            <FileText className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">견적서 보기</span>
          </Button>

          {/* 거래명세서 보기 */}
          <Button
            onClick={onTransactionView}
            disabled={totalLocations === 0}
            variant="outline"
            size="sm"
            className="md:size-default md:px-6"
          >
            <ClipboardList className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">거래명세서 보기</span>
          </Button>

          {/* 수식보기 - 개발환경(local/development)에서만 표시 */}
          {onFormulaView && ['local', 'development'].includes(process.env.NEXT_PUBLIC_APP_ENV || '') && (
            <Button
              onClick={onFormulaView}
              disabled={!hasBomResult}
              variant="outline"
              size="sm"
              className="border-purple-300 text-purple-600 hover:bg-purple-50 md:size-default md:px-6"
            >
              <Calculator className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">수식보기</span>
            </Button>
          )}

          {/* 수정 - view 모드에서만 표시, 생산지시 존재 시 숨김 */}
          {isViewMode && onEdit && isEditable && (
            <Button
              onClick={onEdit}
              variant="outline"
              size="sm"
              className="md:size-default md:px-6"
            >
              <Pencil className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">수정</span>
            </Button>
          )}

          {/* 할인하기 - view 모드 또는 수정 불가 시 비활성 */}
          {onDiscount && (
            <Button
              onClick={onDiscount}
              disabled={isViewMode || !isEditable}
              variant="outline"
              size="sm"
              className="border-orange-300 text-orange-600 hover:bg-orange-50 md:size-default md:px-6"
            >
              <Percent className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">할인하기</span>
            </Button>
          )}

          {/* 저장 버튼 - edit 모드에서만 표시 (draft 유지, 확정하지 않음) */}
          {!isViewMode && (
            <Button
              onClick={onSave}
              disabled={isSaving || !isEditable}
              size="sm"
              className="bg-slate-500 hover:bg-slate-600 text-white md:size-default md:px-6"
            >
              {isSaving ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Save className="h-4 w-4 md:mr-2" />
              )}
              <span className="hidden md:inline">저장</span>
            </Button>
          )}

          {/* 견적확정 - draft 상태에서만 표시 (final/converted 제외) */}
          {status !== "final" && status !== "converted" && (
            <Button
              onClick={onFinalize}
              disabled={isSaving || totalAmount === 0 || !isEditable}
              size="sm"
              className="bg-blue-600 hover:bg-blue-700 text-white md:size-default md:px-6"
            >
              {isSaving ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Check className="h-4 w-4 md:mr-2" />
              )}
              <span className="hidden md:inline">견적확정</span>
            </Button>
          )}

          {/* 수주등록/수주보기 - view 모드에서 final 또는 converted 상태일 때 표시 */}
          {isViewMode && (status === "final" || status === "converted") && (orderId ? (
            onOrderView && (
              <Button
                onClick={onOrderView}
                size="sm"
                className="bg-blue-600 hover:bg-blue-700 text-white md:size-default md:px-6"
              >
                <ClipboardList className="h-4 w-4 md:mr-2" />
                <span className="hidden md:inline">수주 보기</span>
              </Button>
            )
          ) : (
            onOrderRegister && (
              <Button
                onClick={onOrderRegister}
                size="sm"
                className="bg-green-600 hover:bg-green-700 text-white md:size-default md:px-6"
              >
                <ClipboardList className="h-4 w-4 md:mr-2" />
                <span className="hidden md:inline">수주등록</span>
              </Button>
            )
          ))}
        </div>
      </div>
    </div>
  );
}