import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { SystemAdminDashboard } from "./SystemAdminDashboard";
import { AccountantDashboard } from "./AccountantDashboard";
import { SalesManagerDashboard } from "./SalesManagerDashboard";
import { WidgetManager } from "./WidgetManager";
import { Widget, DEFAULT_CEO_WIDGETS } from "./widgets/WidgetTypes";
import { useDeveloperMode } from "./contexts/DeveloperModeContext";
import { SalesOverviewWidget } from "./widgets/SalesOverviewWidget";
import { TopCustomersWidget } from "./widgets/TopCustomersWidget";
import { ProductionStatusWidget } from "./widgets/ProductionStatusWidget";
import { QualityStatusWidget } from "./widgets/QualityStatusWidget";
import { SalesTrendWidget } from "./widgets/SalesTrendWidget";
import { ScheduleCalendarWidget } from "./widgets/ScheduleCalendarWidget";
import { InventoryStatusWidget } from "./widgets/InventoryStatusWidget";
import { ProcessOverviewWidget } from "./widgets/ProcessOverviewWidget";
import { DailySummaryWidget } from "./widgets/DailySummaryWidget";
import { ReceivablesWidget } from "./widgets/ReceivablesWidget";
import { CashFlowWidget } from "./widgets/CashFlowWidget";
import { SalesAchievementWidget } from "./widgets/SalesAchievementWidget";
import { SalesTrendChartWidget } from "./widgets/SalesTrendChartWidget";
import { ReceivablesTrendWidget } from "./widgets/ReceivablesTrendWidget";
import { PurchaseStatusWidget } from "./widgets/PurchaseStatusWidget";
import { HRStatusWidget } from "./widgets/HRStatusWidget";
import { ApprovalStatusWidget } from "./widgets/ApprovalStatusWidget";
import { VehicleStatusWidget } from "./widgets/VehicleStatusWidget";
import { ShippingStatusWidget } from "./widgets/ShippingStatusWidget";
import { QuickActionsWidget } from "./widgets/QuickActionsWidget";
import { NotificationsWidget } from "./widgets/NotificationsWidget";
import { Settings } from "lucide-react";

interface DashboardProps {
  userRole: string;
}

export function Dashboard({ userRole }: DashboardProps) {
  const { setCurrentMetadata } = useDeveloperMode();
  
  // 모바일 감지
  const [isMobile, setIsMobile] = useState(false);

  // 위젯 관리 상태 (모든 hooks를 최상단에 선언)
  const [isWidgetManagerOpen, setIsWidgetManagerOpen] = useState(false);
  const [widgets, setWidgets] = useState<Widget[]>(() => {
    // 로컬 스토리지에서 위젯 설정 불러오기
    const saved = localStorage.getItem('dashboard-widgets');
    if (saved) {
      try {
        const parsedWidgets = JSON.parse(saved);
        // 기존 위젯에 columns 속성이 없으면 추가
        const updatedWidgets = parsedWidgets.map((w: Widget) => ({
          ...w,
          columns: w.columns || 2
        }));
        // 저장된 위젯이 있으면 사용
        if (updatedWidgets.length > 0) {
          return updatedWidgets;
        }
      } catch (e) {
        console.error('Failed to parse saved widgets:', e);
      }
    }
    // 저장된 위젯이 없거나 파싱 실패시 기본 위젯 사용
    return DEFAULT_CEO_WIDGETS;
  });

  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);
  
  // 위젯 설정 저장
  useEffect(() => {
    localStorage.setItem('dashboard-widgets', JSON.stringify(widgets));
  }, [widgets]);
  
  // 개발자 메타데이터 설정
  useEffect(() => {
    setCurrentMetadata({
      componentName: '대시보드',
      pagePath: '/components/Dashboard.tsx',
      description: '역할별 맞춤형 위젯 기반 대시보드 시스템',
      
      apis: [
        {
          endpoint: '/api/v1/dashboard/widgets',
          method: 'GET',
          description: '사용자별 위젯 설정 조회',
          queryParams: [
            { name: 'userId', type: 'string', required: true, description: '사용자 ID' },
          ],
          responseBody: {
            success: true,
            data: {
              widgets: [
                { id: 'sales-overview', type: 'sales-overview', enabled: true, columns: 2, order: 1 }
              ]
            }
          }
        },
        {
          endpoint: '/api/v1/dashboard/stats',
          method: 'GET',
          description: '대시보드 통계 데이터 조회',
          queryParams: [
            { name: 'period', type: 'string', required: false, description: '기간 (today, week, month, year)' },
          ],
          responseBody: {
            success: true,
            data: {
              sales: { total: 15000000, trend: 12.5 },
              production: { total: 45, trend: 8.2 },
              quality: { passRate: 98.5, defectRate: 1.5 },
            }
          }
        },
      ],
      
      dataStructures: [
        {
          name: 'Widget',
          type: 'interface',
          fields: [
            { name: 'id', type: 'string', required: true, description: '위젯 고유 ID' },
            { name: 'type', type: 'string', required: true, description: '위젯 타입' },
            { name: 'enabled', type: 'boolean', required: true, description: '활성화 여부' },
            { name: 'columns', type: 'number', required: true, description: '열 너비 (1-4)' },
            { name: 'order', type: 'number', required: true, description: '표시 순서' },
          ],
        },
      ],
      
      components: [
        {
          name: 'Dashboard',
          path: '/components/Dashboard.tsx',
          children: ['WidgetManager', 'SalesOverviewWidget', 'ProductionStatusWidget', 'QualityStatusWidget'],
        },
      ],
      
      stateManagement: [
        {
          type: 'Local',
          name: 'Component State',
          description: '대시보드 상태 관리',
          methods: [
            'widgets - 위젯 목록 (localStorage 영속화)',
            'isWidgetManagerOpen - 위젯 관리 Dialog 상태',
          ]
        },
      ],
      
      businessLogic: [
        {
          name: '위젯 커스터마이징',
          description: '사용자가 대시보드 위젯을 자유롭게 설정',
          steps: [
            '위젯 관리 버튼 클릭',
            '위젯 활성화/비활성화 토글',
            '위젯 순서 드래그앤드롭 변경',
            '위젯 크기 조정 (1-4열)',
            'localStorage에 자동 저장',
            '대시보드 즉시 반영',
          ]
        },
      ],
    });
    
    return () => {
      setCurrentMetadata(null);
    };
  }, [setCurrentMetadata]);
  
  // 시스템관리자인 경우 SystemAdminDashboard 렌더링
  if (userRole === "SystemAdmin") {
    return <SystemAdminDashboard />;
  }

  // 회계담당자인 경우 AccountantDashboard 렌더링
  if (userRole === "Accountant") {
    return <AccountantDashboard />;
  }

  // 판매담당자인 경우 SalesManagerDashboard 렌더링
  if (userRole === "SalesManager") {
    return <SalesManagerDashboard />;
  }

  const handleUpdateWidgets = (newWidgets: Widget[]) => {
    setWidgets(newWidgets);
  };

  // 위젯 렌더링 함수 (widget.type으로 체크해야 함!)
  const renderWidget = (widget: Widget) => {
    switch (widget.type) {
      case 'sales-overview':
        return <SalesOverviewWidget />;
      case 'top-customers':
        return <TopCustomersWidget />;
      case 'production-status':
        return <ProductionStatusWidget />;
      case 'quality-status':
        return <QualityStatusWidget />;
      case 'sales-trend':
        return <SalesTrendWidget />;
      case 'schedule-calendar':
        return <ScheduleCalendarWidget />;
      case 'inventory-status':
        return <InventoryStatusWidget />;
      case 'process-overview':
        return <ProcessOverviewWidget />;
      case 'daily-summary':
        return <DailySummaryWidget />;
      case 'receivables':
        return <ReceivablesWidget />;
      case 'cash-flow':
        return <CashFlowWidget />;
      case 'sales-achievement':
        return <SalesAchievementWidget />;
      case 'sales-trend-chart':
        return <SalesTrendChartWidget />;
      case 'receivables-trend':
        return <ReceivablesTrendWidget />;
      case 'purchase-status':
        return <PurchaseStatusWidget />;
      case 'hr-status':
        return <HRStatusWidget />;
      case 'approval-status':
        return <ApprovalStatusWidget />;
      case 'vehicle-status':
        return <VehicleStatusWidget />;
      case 'shipping-status':
        return <ShippingStatusWidget />;
      case 'quick-actions':
        return <QuickActionsWidget />;
      case 'notifications':
        return <NotificationsWidget />;
      default:
        return null;
    }
  };

  // 활성화된 위젯만 필터링
  const activeWidgets = widgets.filter(w => w.enabled);

  // 위젯 초기화 함수
  const handleResetWidgets = () => {
    localStorage.removeItem('dashboard-widgets');
    setWidgets(DEFAULT_CEO_WIDGETS);
  };

  // ROW 기반 레이아웃 렌더링
  const renderWidgetLayout = () => {
    // 활성화된 위젯이 없으면 안내 메시지 표시
    if (activeWidgets.length === 0) {
      return (
        <div className="flex flex-col items-center justify-center py-20 px-4 border-2 border-dashed rounded-lg">
          <p className="text-muted-foreground mb-4">표시할 위젯이 없습니다</p>
          <p className="text-sm text-muted-foreground mb-6">
            우측 상단의 '위젯 관리' 버튼을 클릭하여 위젯을 추가하세요
          </p>
          <Button variant="outline" onClick={() => setIsWidgetManagerOpen(true)}>
            위젯 추가
          </Button>
        </div>
      );
    }

    // 모바일에서는 모든 위젯을 1열로 표시
    if (isMobile) {
      return (
        <div className="space-y-4">
          {activeWidgets.map((widget) => (
            <div key={widget.id}>
              {renderWidget(widget)}
            </div>
          ))}
        </div>
      );
    }

    // 데스크톱에서는 ROW 기반 레이아웃
    const rows: Widget[][] = [];
    let currentRow: Widget[] = [];
    let currentRowColumns = 0;

    activeWidgets.forEach((widget) => {
      const widgetColumns = widget.columns || 2;
      
      if (currentRowColumns + widgetColumns > 4) {
        if (currentRow.length > 0) {
          rows.push(currentRow);
        }
        currentRow = [widget];
        currentRowColumns = widgetColumns;
      } else {
        currentRow.push(widget);
        currentRowColumns += widgetColumns;
      }
    });

    if (currentRow.length > 0) {
      rows.push(currentRow);
    }

    return (
      <div className="space-y-4">
        {rows.map((row, rowIndex) => (
          <div key={rowIndex} className="grid grid-cols-4 gap-4">
            {row.map((widget) => {
              const colSpan = widget.columns || 2;
              // Tailwind의 동적 클래스는 작동하지 않으므로 조건부로 정적 클래스 사용
              const colSpanClass = 
                colSpan === 1 ? 'col-span-1' :
                colSpan === 2 ? 'col-span-2' :
                colSpan === 3 ? 'col-span-3' :
                'col-span-4';
              
              return (
                <div
                  key={widget.id}
                  className={colSpanClass}
                >
                  {renderWidget(widget)}
                </div>
              );
            })}
          </div>
        ))}
      </div>
    );
  };

  return (
    <div className="p-4 md:p-6 space-y-4 md:space-y-6">
      {/* 헤더 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">대시보드</h1>
          <p className="text-sm text-muted-foreground">
            {userRole === "CEO" && "대표이사 대시보드"}
            {userRole === "ProductionManager" && "생산관리자 대시보드"}
            {userRole === "Worker" && "작업자 대시보드"}
          </p>
        </div>
        {userRole === "CEO" && (
          <div className="flex gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleResetWidgets}
              title="위젯 설정 초기화"
            >
              초기화
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsWidgetManagerOpen(true)}
            >
              <Settings className="h-4 w-4 mr-2" />
              위젯 관리
            </Button>
          </div>
        )}
      </div>

      {/* 위젯 레이아웃 */}
      {renderWidgetLayout()}

      {/* 위젯 매니저 */}
      <WidgetManager
        isOpen={isWidgetManagerOpen}
        onClose={() => setIsWidgetManagerOpen(false)}
        widgets={widgets}
        onUpdateWidgets={handleUpdateWidgets}
      />
    </div>
  );
}