import { useState, useEffect } from "react";
import { Button } from "./ui/button";
import { Card, CardContent } from "./ui/card";
import { Badge } from "./ui/badge";
import { Switch } from "./ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { 
  Settings, 
  Plus, 
  Trash2, 
  GripVertical,
  DollarSign,
  Target,
  Users,
  TrendingUp,
  Factory,
  CheckCircle,
  Package,
  UserCheck,
  Calendar,
  Truck,
  ShoppingBag,
  BarChart3,
  Zap,
  Bell,
  FileCheck,
  Activity,
  CreditCard,
  Banknote,
  Clock
} from "lucide-react";
import { Widget, WidgetType, WIDGET_METADATA } from "./widgets/WidgetTypes";
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { CommonBottomSheet } from "./templates/CommonBottomSheet";

interface WidgetManagerProps {
  isOpen: boolean;
  onClose: () => void;
  widgets: Widget[];
  onUpdateWidgets: (widgets: Widget[]) => void;
}

// 아이콘 매핑
const ICON_MAP: Record<string, any> = {
  'DollarSign': DollarSign,
  'Target': Target,
  'Users': Users,
  'TrendingUp': TrendingUp,
  'Factory': Factory,
  'CheckCircle': CheckCircle,
  'Package': Package,
  'UserCheck': UserCheck,
  'Calendar': Calendar,
  'Truck': Truck,
  'ShoppingBag': ShoppingBag,
  'BarChart3': BarChart3,
  'Zap': Zap,
  'Bell': Bell,
  'FileCheck': FileCheck,
  'Activity': Activity,
  'CreditCard': CreditCard,
  'Banknote': Banknote,
  'Clock': Clock
};

// 정렬 가능한 위젯 아이템
function SortableWidgetItem({ widget, onToggle, onDelete, onColumnsChange, isMobile }: { 
  widget: Widget; 
  onToggle: (id: string) => void;
  onDelete: (id: string) => void;
  onColumnsChange: (id: string, columns: 1 | 2 | 3 | 4) => void;
  isMobile?: boolean;
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ id: widget.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1
  };

  const IconComponent = ICON_MAP[WIDGET_METADATA[widget.type].icon];

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`flex items-center gap-3 p-3 bg-card border rounded-lg ${isDragging ? 'shadow-lg' : ''}`}
    >
      <div {...attributes} {...listeners} className="cursor-grab active:cursor-grabbing flex-shrink-0">
        <GripVertical className="h-5 w-5 text-muted-foreground" />
      </div>
      <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
        {IconComponent && <IconComponent className="h-4 w-4 text-primary" />}
      </div>
      <div className="flex-1 min-w-0">
        <div className="font-medium text-sm">{widget.title}</div>
        <div className="text-xs text-muted-foreground truncate">{widget.description}</div>
      </div>
      {/* ROW 분할 선택 - 모바일에서는 숨김 */}
      {!isMobile && (
        <div className="flex items-center gap-1 px-2 py-1 border border-border rounded-md bg-background flex-shrink-0">
          <span className="text-xs text-muted-foreground">너비:</span>
          <button
            onClick={(e) => {
              e.stopPropagation();
              onColumnsChange(widget.id, 4);
            }}
            className={`px-2 py-0.5 text-xs rounded ${
              widget.columns === 4 
                ? 'bg-primary text-primary-foreground' 
                : 'bg-muted text-muted-foreground hover:bg-muted/80'
            }`}
            title="전체"
          >
            전체
          </button>
          <button
            onClick={(e) => {
              e.stopPropagation();
              onColumnsChange(widget.id, 2);
            }}
            className={`px-2 py-0.5 text-xs rounded ${
              widget.columns === 2 
                ? 'bg-primary text-primary-foreground' 
                : 'bg-muted text-muted-foreground hover:bg-muted/80'
            }`}
            title="절반"
          >
            1/2
          </button>
        </div>
      )}
      <Switch
        checked={widget.enabled}
        onCheckedChange={() => onToggle(widget.id)}
        className="flex-shrink-0"
      />
      <Button
        variant="ghost"
        size="sm"
        onClick={() => onDelete(widget.id)}
        className="text-red-600 hover:text-red-700 hover:bg-red-50 flex-shrink-0 h-8 w-8 p-0"
      >
        <Trash2 className="h-4 w-4" />
      </Button>
    </div>
  );
}

export function WidgetManager({ isOpen, onClose, widgets, onUpdateWidgets }: WidgetManagerProps) {
  const [localWidgets, setLocalWidgets] = useState<Widget[]>(widgets);
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [isMobile, setIsMobile] = useState(false);

  // 모바일 감지
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  // 카테고리 목록
  const categories = ["all", "매출/재무", "생산", "품질", "자재/재고", "인사", "일정", "결재", "기타"];

  // 추가 가능한 위젯 목록
  const availableWidgets = (Object.keys(WIDGET_METADATA) as WidgetType[]).filter(
    type => !localWidgets.some(w => w.type === type)
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (over && active.id !== over.id) {
      setLocalWidgets((items) => {
        const oldIndex = items.findIndex(item => item.id === active.id);
        const newIndex = items.findIndex(item => item.id === over.id);
        
        const newItems = arrayMove(items, oldIndex, newIndex);
        // order 업데이트
        return newItems.map((item, index) => ({ ...item, order: index + 1 }));
      });
    }
  };

  const handleToggleWidget = (id: string) => {
    setLocalWidgets(prev =>
      prev.map(w => w.id === id ? { ...w, enabled: !w.enabled } : w)
    );
  };

  const handleDeleteWidget = (id: string) => {
    setLocalWidgets(prev => prev.filter(w => w.id !== id));
  };

  const handleColumnsChange = (id: string, columns: 1 | 2 | 3 | 4) => {
    setLocalWidgets(prev =>
      prev.map(w => w.id === id ? { ...w, columns } : w)
    );
  };

  const handleAddWidget = (type: WidgetType) => {
    const metadata = WIDGET_METADATA[type];
    const newWidget: Widget = {
      id: `w${Date.now()}`,
      type,
      title: metadata.title,
      description: metadata.description,
      size: metadata.defaultSize,
      columns: 2, // 기본값: 2분할 (절반 너비)
      order: localWidgets.length + 1,
      enabled: true
    };
    setLocalWidgets(prev => [...prev, newWidget]);
  };

  const handleSave = () => {
    onUpdateWidgets(localWidgets);
    onClose();
  };

  const handleReset = () => {
    if (confirm("기본 설정으로 초기화하시겠습니까?")) {
      // 기본 위젯 설정으로 리셋하는 로직은 부모 컴포넌트에서 처리
      onClose();
    }
  };

  const filteredAvailableWidgets = selectedCategory === "all" 
    ? availableWidgets
    : availableWidgets.filter(type => WIDGET_METADATA[type].category === selectedCategory);

  // 공통 콘텐츠
  const content = (
    <Tabs defaultValue="current" className="flex-1 overflow-hidden flex flex-col">
      <TabsList className="grid w-full grid-cols-2">
        <TabsTrigger value="current">현재 위젯</TabsTrigger>
        <TabsTrigger value="add">위젯 추가</TabsTrigger>
      </TabsList>

      <TabsContent value="current" className="flex-1 overflow-auto mt-4">
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mb-3 pb-3 border-b">
          <div className="text-sm text-muted-foreground">
            활성화된 위젯: <span className="font-semibold text-foreground">{localWidgets.filter(w => w.enabled).length}</span> / {localWidgets.length}
          </div>
          <Button variant="outline" size="sm" onClick={handleReset} className="w-full sm:w-auto">
            기본값으로 초기화
          </Button>
        </div>

        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <SortableContext
            items={localWidgets.map(w => w.id)}
            strategy={verticalListSortingStrategy}
          >
            <div className="space-y-1.5">
              {localWidgets.map(widget => (
                <SortableWidgetItem
                  key={widget.id}
                  widget={widget}
                  onToggle={handleToggleWidget}
                  onDelete={handleDeleteWidget}
                  onColumnsChange={handleColumnsChange}
                  isMobile={isMobile}
                />
              ))}
            </div>
          </SortableContext>
        </DndContext>

        {localWidgets.length === 0 && (
          <div className="text-center py-12 text-muted-foreground">
            <Package className="h-12 w-12 mx-auto mb-3 opacity-50" />
            <p>위젯이 없습니다. 새로운 위젯을 추가해보세요.</p>
          </div>
        )}
      </TabsContent>

      <TabsContent value="add" className="flex-1 overflow-auto mt-4">
        <div className="mb-3 pb-3 border-b">
          <div className="flex gap-2 flex-wrap">
            {categories.map(cat => (
              <Button
                key={cat}
                variant={selectedCategory === cat ? "default" : "outline"}
                size="sm"
                onClick={() => setSelectedCategory(cat)}
              >
                {cat === "all" ? "전체" : cat}
              </Button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-2.5">
          {filteredAvailableWidgets.map(type => {
            const metadata = WIDGET_METADATA[type];
            const IconComponent = ICON_MAP[metadata.icon];
            
            return (
              <Card key={type} className="hover:shadow-md transition-shadow">
                <CardContent className="p-3">
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex items-start gap-2 flex-1 min-w-0">
                      <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                        {IconComponent && <IconComponent className="h-4 w-4 text-primary" />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-sm mb-0.5">{metadata.title}</div>
                        <div className="text-xs text-muted-foreground mb-1.5 line-clamp-2">
                          {metadata.description}
                        </div>
                        <Badge variant="outline" className="text-xs">{metadata.category}</Badge>
                      </div>
                    </div>
                    <Button
                      size="sm"
                      onClick={() => handleAddWidget(type)}
                      className="flex-shrink-0 h-8"
                    >
                      <Plus className="h-3 w-3 mr-1" />
                      항목추가
                    </Button>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>

        {filteredAvailableWidgets.length === 0 && (
          <div className="text-center py-12 text-muted-foreground">
            <CheckCircle className="h-12 w-12 mx-auto mb-3 opacity-50" />
            <p>추가할 수 있는 위젯이 없습니다.</p>
          </div>
        )}
      </TabsContent>
    </Tabs>
  );

  return (
    <CommonBottomSheet
      isOpen={isOpen}
      onClose={onClose}
      title="위젯 관리"
      description="대시보드에 표시할 위젯을 선택하고 순서를 변경할 수 있습니다. 각 위젯의 너비를 전체 또는 절반(1/2)으로 설정할 수 있습니다."
      maxWidth="5xl"
      maxHeight="85vh"
      showFooter={true}
      saveButtonText="저장"
      cancelButtonText="취소"
      onSave={handleSave}
      onCancel={onClose}
    >
      {content}
    </CommonBottomSheet>
  );
}