'use client';

/**
 * DevToolbar - 개발/테스트용 플로팅 툴바
 *
 * 화면 하단에 플로팅으로 표시되며,
 * 각 단계(견적→수주→작업지시→완료→출하)의 폼을 자동으로 채울 수 있습니다.
 *
 * 기능:
 * - 현재 페이지에서 활성화: 버튼 클릭 시 폼 자동 채우기
 * - 다른 페이지에서 비활성화: 버튼 클릭 시 해당 페이지로 이동
 *
 * 환경변수로 활성화/비활성화:
 * NEXT_PUBLIC_DEV_TOOLBAR_ENABLED=true
 */

import { useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import {
  FileText,      // 견적
  ClipboardList, // 수주
  Wrench,        // 작업지시
  CheckCircle2,  // 완료
  Truck,         // 출하
  ChevronDown,
  ChevronUp,
  X,
  Loader2,
  Play,
  RotateCcw,
  // 회계 아이콘
  ArrowDownToLine,  // 입금
  ArrowUpFromLine,  // 출금
  Receipt,          // 매입(지출결의서)
  CreditCard,       // 카드
  // 기준정보 아이콘
  Building2,        // 거래처
  // 자재 아이콘
  PackageCheck,     // 입고
  // Dev 도구 아이콘
  Layers,           // 컴포넌트 레지스트리
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useDevFillContext, type DevFillPageType } from './DevFillContext';

// 페이지 경로와 타입 매핑 (pathname만으로 매칭되는 패턴)
const PAGE_PATTERNS: { pattern: RegExp; type: DevFillPageType; label: string }[] = [
  // 판매/생산 플로우 (V2 URL 패턴 적용)
  { pattern: /\/quote-management\/new$/, type: 'quoteV2', label: '견적V2' },
  { pattern: /\/quote-management\/\d+$/, type: 'quoteV2', label: '견적V2' },
  { pattern: /\/order-management-sales\/new/, type: 'order', label: '수주' },
  { pattern: /\/order-management-sales\/\d+\/edit/, type: 'order', label: '수주' },
  { pattern: /\/work-orders\/create/, type: 'workOrder', label: '작업지시' },
  { pattern: /\/work-orders\/\d+\/edit/, type: 'workOrder', label: '작업지시' },
  { pattern: /\/work-orders\/\d+$/, type: 'workOrderComplete', label: '작업완료' },
  { pattern: /\/shipments\/new/, type: 'shipment', label: '출하' },
  { pattern: /\/shipments\/\d+\/edit/, type: 'shipment', label: '출하' },
  // 회계 플로우 (mode=new 사용하는 페이지는 아래 MODE_NEW_PAGES에서 처리)
  { pattern: /\/approval\/draft\/new/, type: 'purchaseApproval', label: '매입' },
  { pattern: /\/accounting\/card-transactions\/new/, type: 'cardTransaction', label: '카드' },
  // 기준정보
  { pattern: /\/client-management-sales-admin\/new/, type: 'client', label: '거래처' },
  // 자재
  { pattern: /\/material\/receiving-management\/new/, type: 'receiving', label: '입고' },
];

// ?mode=new 쿼리 파라미터를 사용하는 페이지 매핑
// 기존 /new 경로에서 ?mode=new로 마이그레이션 중인 페이지들
const MODE_NEW_PAGES: { pattern: RegExp; type: DevFillPageType; label: string }[] = [
  // 판매/생산 플로우
  { pattern: /\/order-management-sales$/, type: 'order', label: '수주' },
  // 회계 플로우
  { pattern: /\/accounting\/deposits$/, type: 'deposit', label: '입금' },
  { pattern: /\/accounting\/withdrawals$/, type: 'withdrawal', label: '출금' },
];

// 플로우 단계 정의
const FLOW_STEPS: { type: DevFillPageType; label: string; icon: typeof FileText; path: string }[] = [
  { type: 'quoteV2', label: '견적', icon: FileText, path: '/sales/quote-management/new' },
  { type: 'order', label: '수주', icon: ClipboardList, path: '/sales/order-management-sales?mode=new' },
  { type: 'workOrder', label: '작업지시', icon: Wrench, path: '/production/work-orders/create' },
  { type: 'workOrderComplete', label: '완료', icon: CheckCircle2, path: '' }, // 상세 페이지에서 처리
  { type: 'shipment', label: '출하', icon: Truck, path: '/outbound/shipments/new' },
];

// 회계 단계 정의
const ACCOUNTING_STEPS: { type: DevFillPageType; label: string; icon: typeof FileText; path: string; fillEnabled: boolean }[] = [
  { type: 'deposit', label: '입금', icon: ArrowDownToLine, path: '/accounting/deposits?mode=new', fillEnabled: true },
  { type: 'withdrawal', label: '출금', icon: ArrowUpFromLine, path: '/accounting/withdrawals?mode=new', fillEnabled: true },
  { type: 'purchaseApproval', label: '매입', icon: Receipt, path: '/approval/draft/new', fillEnabled: true },
  { type: 'cardTransaction', label: '카드', icon: CreditCard, path: '/accounting/card-transactions/new', fillEnabled: true },
];

// 기준정보 단계 정의
const MASTER_DATA_STEPS: { type: DevFillPageType; label: string; icon: typeof FileText; path: string; fillEnabled: boolean }[] = [
  { type: 'client', label: '거래처', icon: Building2, path: '/sales/client-management-sales-admin/new', fillEnabled: true },
];

// 자재 단계 정의
const MATERIAL_STEPS: { type: DevFillPageType; label: string; icon: typeof FileText; path: string; fillEnabled: boolean }[] = [
  { type: 'receiving', label: '입고', icon: PackageCheck, path: '/material/receiving-management/new', fillEnabled: true },
];

export function DevToolbar() {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();
  const {
    isEnabled,
    isVisible,
    setIsVisible,
    currentPage: _currentPage,
    fillForm,
    hasRegisteredForm,
    flowData,
    clearFlowData,
  } = useDevFillContext();

  const [isExpanded, setIsExpanded] = useState(true);
  const [isLoading, setIsLoading] = useState<DevFillPageType | null>(null);

  // 현재 locale 추출 (유효한 locale만 인식)
  const VALID_LOCALES = ['ko', 'en'];
  const firstSegment = pathname.split('/')[1];
  const locale = VALID_LOCALES.includes(firstSegment) ? firstSegment : '';

  // mode=new 쿼리 파라미터 확인
  const isNewMode = searchParams.get('mode') === 'new';

  // 비활성화 시 렌더링하지 않음
  if (!isEnabled) return null;

  // 숨김 상태일 때 작은 버튼만 표시
  if (!isVisible) {
    return (
      <div className="fixed bottom-20 right-4 z-[9999]">
        <Button
          size="sm"
          variant="outline"
          className="bg-yellow-100 border-yellow-400 text-yellow-800 hover:bg-yellow-200 shadow-lg"
          onClick={() => setIsVisible(true)}
        >
          <Play className="w-4 h-4 mr-1" />
          Dev
        </Button>
      </div>
    );
  }

  // 현재 페이지 타입 감지
  // 1. 먼저 ?mode=new를 사용하는 페이지 체크
  const modeNewPage = isNewMode
    ? MODE_NEW_PAGES.find(p => p.pattern.test(pathname))
    : null;
  // 2. 일반 패턴 매칭
  const patternMatchedPage = PAGE_PATTERNS.find(p => p.pattern.test(pathname));
  // 3. mode=new 페이지 우선, 없으면 일반 패턴 매칭
  const detectedPage = modeNewPage || patternMatchedPage;
  const activePage = detectedPage?.type || null;

  // 폼 채우기 실행
  const handleFillForm = async (pageType: DevFillPageType) => {
    if (!hasRegisteredForm(pageType)) {
      console.warn(`[DevToolbar] Form not registered for: ${pageType}`);
      return;
    }

    setIsLoading(pageType);
    try {
      await fillForm(pageType, flowData);
    } catch (err) {
      console.error('[DevToolbar] Fill form error:', err);
    } finally {
      setIsLoading(null);
    }
  };

  // 페이지 이동
  const handleNavigate = (path: string) => {
    if (path) {
      router.push(locale ? `/${locale}${path}` : path);
    }
  };

  // 플로우 데이터 표시
  const hasFlowData = flowData.quoteId || flowData.orderId || flowData.workOrderId || flowData.lotNo;

  return (
    <div className="fixed bottom-12 left-1/2 -translate-x-1/2 z-[9999] w-[calc(100vw-1rem)] sm:w-auto sm:max-w-[calc(100vw-1rem)]">
      <div className="bg-yellow-50 border-2 border-yellow-400 rounded-lg shadow-2xl overflow-hidden">
        {/* 헤더 */}
        <div className="flex items-center justify-between px-2 sm:px-3 py-1.5 sm:py-2 bg-yellow-100 border-b border-yellow-300">
          <div className="flex items-center gap-2">
            <Badge variant="outline" className="bg-yellow-200 border-yellow-500 text-yellow-800">
              DEV MODE
            </Badge>
            <Button
              size="sm"
              variant="ghost"
              className="h-6 px-1.5 text-yellow-700 hover:bg-yellow-200"
              onClick={() => handleNavigate('/dev/component-registry')}
              title="컴포넌트 레지스트리"
            >
              <Layers className="w-3.5 h-3.5" />
            </Button>
            {detectedPage && (
              <span className="text-sm text-yellow-700">
                현재: <strong>{detectedPage.label}</strong>
              </span>
            )}
            {hasFlowData && (
              <Badge variant="secondary" className="text-xs">
                {flowData.quoteId && `견적#${flowData.quoteId}`}
                {flowData.orderId && ` → 수주#${flowData.orderId}`}
                {flowData.workOrderId && ` → 작업#${flowData.workOrderId}`}
              </Badge>
            )}
            {/* 축소 상태에서 채우기 버튼 */}
            {!isExpanded && activePage && hasRegisteredForm(activePage) && (
              <Button
                size="sm"
                variant="default"
                disabled={isLoading === activePage}
                className="h-6 bg-yellow-500 hover:bg-yellow-600 text-white text-xs px-2"
                onClick={() => handleFillForm(activePage)}
                title="폼 자동 채우기"
              >
                {isLoading === activePage ? (
                  <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                ) : (
                  <Play className="w-3 h-3 mr-1" />
                )}
                채우기
              </Button>
            )}
          </div>
          <div className="flex items-center gap-1">
            {hasFlowData && (
              <Button
                size="icon"
                variant="ghost"
                className="h-6 w-6 text-yellow-700 hover:bg-yellow-200"
                onClick={clearFlowData}
                title="플로우 초기화"
              >
                <RotateCcw className="w-3 h-3" />
              </Button>
            )}
            <Button
              size="icon"
              variant="ghost"
              className="h-6 w-6 text-yellow-700 hover:bg-yellow-200"
              onClick={() => setIsExpanded(!isExpanded)}
            >
              {isExpanded ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />}
            </Button>
            <Button
              size="icon"
              variant="ghost"
              className="h-6 w-6 text-yellow-700 hover:bg-yellow-200"
              onClick={() => setIsVisible(false)}
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
        </div>

        {/* 판매/생산 플로우 버튼 영역 */}
        {isExpanded && (
          <div className="flex flex-wrap items-center gap-1.5 sm:gap-2 px-2 sm:px-3 py-2 sm:py-3">
            {FLOW_STEPS.map((step, index) => {
              const Icon = step.icon;
              const isActive = activePage === step.type;
              const isRegistered = hasRegisteredForm(step.type);
              const isCurrentLoading = isLoading === step.type;
              const hasPath = !!step.path;

              // 완료 버튼은 상세 페이지에서만 활성화 (이동 경로 없음)
              if (step.type === 'workOrderComplete' && !isActive) {
                return (
                  <div key={step.type} className="flex items-center">
                    {index > 0 && <span className="text-yellow-400 mx-1">→</span>}
                    <Button
                      size="sm"
                      variant="outline"
                      disabled
                      className="opacity-50"
                      title="작업지시 상세 페이지에서 사용 가능"
                    >
                      <Icon className="w-4 h-4 mr-1" />
                      {step.label}
                    </Button>
                  </div>
                );
              }

              // 활성화된 페이지: 폼 채우기
              if (isActive) {
                return (
                  <div key={step.type} className="flex items-center">
                    {index > 0 && <span className="text-yellow-400 mx-1">→</span>}
                    <Button
                      size="sm"
                      variant="default"
                      disabled={!isRegistered || isCurrentLoading}
                      className="bg-yellow-500 hover:bg-yellow-600 text-white border-yellow-600"
                      onClick={() => handleFillForm(step.type)}
                      title="폼 자동 채우기"
                    >
                      {isCurrentLoading ? (
                        <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                      ) : (
                        <Icon className="w-4 h-4 mr-1" />
                      )}
                      {step.label} 채우기
                    </Button>
                  </div>
                );
              }

              // 비활성화된 페이지: 해당 페이지로 이동
              return (
                <div key={step.type} className="flex items-center">
                  {index > 0 && <span className="text-yellow-400 mx-1">→</span>}
                  <Button
                    size="sm"
                    variant="outline"
                    disabled={!hasPath}
                    className="border-yellow-300 text-yellow-700 hover:bg-yellow-100 hover:border-yellow-500"
                    onClick={() => handleNavigate(step.path)}
                    title={hasPath ? `${step.label} 페이지로 이동` : '이동 경로 없음'}
                  >
                    <Icon className="w-4 h-4 mr-1" />
                    {step.label}
                  </Button>
                </div>
              );
            })}
          </div>
        )}

        {/* 2행: 회계 + 기준정보 + 자재 버튼 영역 */}
        {isExpanded && (
          <div className="flex flex-wrap items-center gap-1.5 sm:gap-2 px-2 sm:px-3 pb-2 sm:pb-3 border-t border-yellow-300 pt-2 sm:pt-3">
            {/* 회계 */}
            <span className="text-xs text-yellow-600 font-medium mr-1">회계:</span>
            {ACCOUNTING_STEPS.map((step) => {
              const Icon = step.icon;
              const isActive = activePage === step.type;
              const isRegistered = hasRegisteredForm(step.type);
              const isCurrentLoading = isLoading === step.type;

              if (isActive && step.fillEnabled) {
                return (
                  <Button
                    key={step.type}
                    size="sm"
                    variant="default"
                    disabled={!isRegistered || isCurrentLoading}
                    className="bg-blue-500 hover:bg-blue-600 text-white border-blue-600"
                    onClick={() => handleFillForm(step.type)}
                    title="폼 자동 채우기"
                  >
                    {isCurrentLoading ? (
                      <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                    ) : (
                      <Icon className="w-4 h-4 mr-1" />
                    )}
                    {step.label} 채우기
                  </Button>
                );
              }

              return (
                <Button
                  key={step.type}
                  size="sm"
                  variant="outline"
                  className={`border-blue-300 text-blue-700 hover:bg-blue-100 hover:border-blue-500 ${isActive ? 'bg-blue-100 border-blue-500' : ''}`}
                  onClick={() => handleNavigate(step.path)}
                  title={`${step.label} 페이지로 이동`}
                >
                  <Icon className="w-4 h-4 mr-1" />
                  {step.label}
                </Button>
              );
            })}

            {/* 구분선 */}
            <div className="w-px h-6 bg-yellow-300 mx-1" />

            {/* 기준정보 */}
            <span className="text-xs text-yellow-600 font-medium mr-1">기준:</span>
            {MASTER_DATA_STEPS.map((step) => {
              const Icon = step.icon;
              const isActive = activePage === step.type;
              const isRegistered = hasRegisteredForm(step.type);
              const isCurrentLoading = isLoading === step.type;

              if (isActive && step.fillEnabled) {
                return (
                  <Button
                    key={step.type}
                    size="sm"
                    variant="default"
                    disabled={!isRegistered || isCurrentLoading}
                    className="bg-green-500 hover:bg-green-600 text-white border-green-600"
                    onClick={() => handleFillForm(step.type)}
                    title="폼 자동 채우기"
                  >
                    {isCurrentLoading ? (
                      <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                    ) : (
                      <Icon className="w-4 h-4 mr-1" />
                    )}
                    {step.label} 채우기
                  </Button>
                );
              }

              return (
                <Button
                  key={step.type}
                  size="sm"
                  variant="outline"
                  className={`border-green-300 text-green-700 hover:bg-green-100 hover:border-green-500 ${isActive ? 'bg-green-100 border-green-500' : ''}`}
                  onClick={() => handleNavigate(step.path)}
                  title={`${step.label} 페이지로 이동`}
                >
                  <Icon className="w-4 h-4 mr-1" />
                  {step.label}
                </Button>
              );
            })}

            {/* 구분선 */}
            <div className="w-px h-6 bg-yellow-300 mx-1" />

            {/* 자재 */}
            <span className="text-xs text-yellow-600 font-medium mr-1">자재:</span>
            {MATERIAL_STEPS.map((step) => {
              const Icon = step.icon;
              const isActive = activePage === step.type;
              const isRegistered = hasRegisteredForm(step.type);
              const isCurrentLoading = isLoading === step.type;

              if (isActive && step.fillEnabled) {
                return (
                  <Button
                    key={step.type}
                    size="sm"
                    variant="default"
                    disabled={!isRegistered || isCurrentLoading}
                    className="bg-purple-500 hover:bg-purple-600 text-white border-purple-600"
                    onClick={() => handleFillForm(step.type)}
                    title="폼 자동 채우기"
                  >
                    {isCurrentLoading ? (
                      <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                    ) : (
                      <Icon className="w-4 h-4 mr-1" />
                    )}
                    {step.label} 채우기
                  </Button>
                );
              }

              return (
                <Button
                  key={step.type}
                  size="sm"
                  variant="outline"
                  className={`border-purple-300 text-purple-700 hover:bg-purple-100 hover:border-purple-500 ${isActive ? 'bg-purple-100 border-purple-500' : ''}`}
                  onClick={() => handleNavigate(step.path)}
                  title={`${step.label} 페이지로 이동`}
                >
                  <Icon className="w-4 h-4 mr-1" />
                  {step.label}
                </Button>
              );
            })}
          </div>
        )}

        {/* 안내 메시지 */}
        {isExpanded && !activePage && (
          <div className="px-3 pb-3">
            <p className="text-xs text-yellow-600">
              견적/수주/작업지시/출하/입금/출금/매입/거래처/입고 페이지에서 자동 채우기가 활성화됩니다
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

export default DevToolbar;