'use client';

import { useState, useRef } from 'react';
import { LayoutGrid, GripVertical, Plus, X, Maximize2, Minimize2, Square } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DashboardSwitcher } from '@/components/business/DashboardSwitcher';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, CartesianGrid, ResponsiveContainer, Tooltip } from 'recharts';
import { formatNumber } from '@/lib/utils/amount';

// ============================================
// Mock 데이터
// ============================================

const cashFlowData = [
  { month: '9월', 입금: 8200, 출금: 6800 },
  { month: '10월', 입금: 9500, 출금: 7200 },
  { month: '11월', 입금: 7800, 출금: 8100 },
  { month: '12월', 입금: 11200, 출금: 7500 },
  { month: '1월', 입금: 9800, 출금: 8900 },
  { month: '2월', 입금: 10500, 출금: 6764 },
];

const expenseData = [
  { name: '매입', value: 5234, color: '#3b82f6' },
  { name: '인건비', value: 3200, color: '#10b981' },
  { name: '운영비', value: 1580, color: '#8b5cf6' },
  { name: '기타', value: 1350, color: '#94a3b8' },
  { name: '카드', value: 985, color: '#f97316' },
];

const receivables = [
  { name: '(주)대한건설', amount: '4,000만', days: 45, status: '정상' },
  { name: '삼성엔지니어링', amount: '1억', days: 92, status: '주의' },
  { name: 'SK에코플랜트', amount: '4,400만', days: 30, status: '정상' },
  { name: 'LG전자', amount: '3,200만', days: 120, status: '위험' },
];

const todaySchedule = [
  { time: '09:00', title: '대한건설 현장 미팅', type: 'meeting' },
  { time: '11:00', title: '삼성엔지니어링 견적 검토', type: 'task' },
  { time: '14:00', title: '월간 실적 보고', type: 'report' },
  { time: '16:00', title: 'SK에코플랜트 납품 확인', type: 'delivery' },
];

const alerts = [
  { id: 1, text: 'LG전자 미수금 120일 경과 (위험)', type: 'danger', time: '10분 전' },
  { id: 2, text: '출장비 정산 승인 요청 (홍킬동)', type: 'warning', time: '30분 전' },
  { id: 3, text: '현대중공업 입금 683만원 확인', type: 'success', time: '1시간 전' },
  { id: 4, text: '서울금속 신규 거래처 등록', type: 'info', time: '2시간 전' },
  { id: 5, text: '전동개폐기 납기 지연 3일', type: 'warning', time: '3시간 전' },
];

// ============================================
// 위젯 타입
// ============================================

interface Widget {
  id: string;
  title: string;
  size: 'sm' | 'md' | 'lg';
  type: 'cashflow' | 'receivable' | 'schedule' | 'expense' | 'kpi' | 'alerts';
}

const defaultWidgets: Widget[] = [
  { id: 'kpi', title: '핵심 KPI', size: 'lg', type: 'kpi' },
  { id: 'cashflow', title: '현금 흐름 추이', size: 'md', type: 'cashflow' },
  { id: 'expense', title: '지출 항목별 비율', size: 'md', type: 'expense' },
  { id: 'receivable', title: '미수금 현황', size: 'md', type: 'receivable' },
  { id: 'schedule', title: '오늘 일정', size: 'md', type: 'schedule' },
  { id: 'alerts', title: '최근 알림', size: 'lg', type: 'alerts' },
];

// ============================================
// 위젯 컴포넌트들
// ============================================

function KpiWidget() {
  const kpis = [
    { label: '현금성 자산', value: '305억', change: '+5.2%', up: true, color: 'text-blue-600', bg: 'bg-blue-50' },
    { label: '당월 매출', value: '12.8억', change: '+8.3%', up: true, color: 'text-green-600', bg: 'bg-green-50' },
    { label: '당월 미수금', value: '10.1억', change: '+2.1%', up: true, color: 'text-red-600', bg: 'bg-red-50' },
    { label: '당월 지출', value: '8.5억', change: '-3.2%', up: false, color: 'text-orange-600', bg: 'bg-orange-50' },
  ];
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
      {kpis.map((kpi) => (
        <div key={kpi.label} className={`${kpi.bg} rounded-xl p-4`}>
          <p className="text-xs text-muted-foreground">{kpi.label}</p>
          <p className={`text-xl font-bold mt-1 ${kpi.color}`}>{kpi.value}</p>
          <p className={`text-xs mt-1 ${kpi.up ? 'text-green-500' : 'text-red-500'}`}>{kpi.change}</p>
        </div>
      ))}
    </div>
  );
}

function CashflowWidget() {
  return (
    <ResponsiveContainer width="100%" height={180}>
      <BarChart data={cashFlowData}>
        <CartesianGrid strokeDasharray="3 3" vertical={false} />
        <XAxis dataKey="month" tick={{ fontSize: 11 }} />
        <YAxis tick={{ fontSize: 11 }} tickFormatter={(v: number) => `${v}만`} width={50} />
        <Tooltip formatter={(v) => `${formatNumber(Number(v ?? 0))}만원`} contentStyle={{ fontSize: '12px', borderRadius: '8px' }} />
        <Bar dataKey="입금" fill="#3b82f6" radius={[3, 3, 0, 0]} maxBarSize={20} />
        <Bar dataKey="출금" fill="#f97316" radius={[3, 3, 0, 0]} maxBarSize={20} />
      </BarChart>
    </ResponsiveContainer>
  );
}

function ExpenseWidget() {
  const chartData = expenseData.map((d) => ({ name: d.name, value: d.value, color: d.color }));
  return (
    <div className="flex items-center gap-4">
      <ResponsiveContainer width="50%" height={160}>
        <PieChart>
          <Pie data={chartData} cx="50%" cy="50%" innerRadius={40} outerRadius={65} dataKey="value" nameKey="name">
            {chartData.map((entry, i) => <Cell key={i} fill={entry.color} />)}
          </Pie>
          <Tooltip formatter={(v) => `${formatNumber(Number(v ?? 0))}만원`} contentStyle={{ fontSize: '12px', borderRadius: '8px' }} />
        </PieChart>
      </ResponsiveContainer>
      <div className="flex-1 space-y-2">
        {expenseData.map((item) => (
          <div key={item.name} className="flex items-center justify-between text-sm">
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: item.color }} />
              <span>{item.name}</span>
            </div>
            <span className="font-medium">{formatNumber(item.value)}만</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ReceivableWidget() {
  return (
    <div className="space-y-2">
      {receivables.map((r) => (
        <div key={r.name} className={`flex items-center justify-between p-2.5 rounded-lg border text-sm ${r.days >= 90 ? 'bg-red-50 border-red-200' : r.days >= 30 ? 'bg-yellow-50 border-yellow-200' : 'border-border'}`}>
          <div>
            <p className="font-medium">{r.name}</p>
            <p className="text-xs text-muted-foreground">{r.days}일 경과</p>
          </div>
          <div className="text-right">
            <p className="font-semibold">{r.amount}</p>
            <StatusBadge status={r.status} />
          </div>
        </div>
      ))}
    </div>
  );
}

function ScheduleWidget() {
  const typeColors: Record<string, string> = { meeting: 'bg-blue-500', task: 'bg-green-500', report: 'bg-orange-500', delivery: 'bg-purple-500' };
  return (
    <div className="space-y-2">
      {todaySchedule.map((s) => (
        <div key={s.time} className="flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/30 transition-colors">
          <span className="text-xs text-muted-foreground w-10 flex-shrink-0">{s.time}</span>
          <div className={`w-2 h-2 rounded-full flex-shrink-0 ${typeColors[s.type] ?? 'bg-gray-400'}`} />
          <span className="text-sm">{s.title}</span>
        </div>
      ))}
    </div>
  );
}

function AlertsWidget() {
  const typeStyles: Record<string, string> = {
    danger: 'border-l-red-500 bg-red-50/50',
    warning: 'border-l-yellow-500 bg-yellow-50/50',
    success: 'border-l-green-500 bg-green-50/50',
    info: 'border-l-blue-500 bg-blue-50/50',
  };
  return (
    <div className="space-y-2">
      {alerts.map((a) => (
        <div key={a.id} className={`flex items-center justify-between p-3 rounded-lg border-l-4 ${typeStyles[a.type]}`}>
          <span className="text-sm">{a.text}</span>
          <span className="text-xs text-muted-foreground flex-shrink-0 ml-3">{a.time}</span>
        </div>
      ))}
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const styles: Record<string, string> = { '정상': 'bg-green-100 text-green-700', '주의': 'bg-yellow-100 text-yellow-700', '위험': 'bg-red-100 text-red-700' };
  return <span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-medium ${styles[status] ?? 'bg-gray-100 text-gray-600'}`}>{status}</span>;
}

// ============================================
// 위젯 렌더러
// ============================================

function renderWidgetContent(type: Widget['type']) {
  switch (type) {
    case 'kpi': return <KpiWidget />;
    case 'cashflow': return <CashflowWidget />;
    case 'expense': return <ExpenseWidget />;
    case 'receivable': return <ReceivableWidget />;
    case 'schedule': return <ScheduleWidget />;
    case 'alerts': return <AlertsWidget />;
  }
}

function sizeClass(size: Widget['size']) {
  switch (size) {
    case 'sm': return 'col-span-1';
    case 'md': return 'col-span-1 xl:col-span-1';
    case 'lg': return 'col-span-1 xl:col-span-2';
  }
}

// ============================================
// 메인 컴포넌트
// ============================================

export function DashboardType3() {
  const [widgets, setWidgets] = useState<Widget[]>(defaultWidgets);
  const [editMode, setEditMode] = useState(false);
  const [showAddPanel, setShowAddPanel] = useState(false);
  const dragIndex = useRef<number | null>(null);
  const [dragOverIdx, setDragOverIdx] = useState<number | null>(null);

  // 현재 배치되지 않은 위젯 목록
  const removedWidgets = defaultWidgets.filter((dw) => !widgets.some((w) => w.id === dw.id));

  // sm → md → lg → sm 순환
  const toggleSize = (id: string) => {
    const cycle: Record<Widget['size'], Widget['size']> = { sm: 'md', md: 'lg', lg: 'sm' };
    setWidgets((prev) =>
      prev.map((w) => (w.id === id ? { ...w, size: cycle[w.size] } : w)),
    );
  };

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

  const addWidget = (widget: Widget) => {
    setWidgets((prev) => [...prev, widget]);
    setShowAddPanel(false);
  };

  const resetWidgets = () => {
    setWidgets(defaultWidgets);
    setShowAddPanel(false);
  };

  // --- Drag & Drop 핸들러 ---
  const handleDragStart = (e: React.DragEvent, idx: number) => {
    dragIndex.current = idx;
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('application/json', JSON.stringify({ type: 'widget', idx }));
  };

  const handleDragOver = (e: React.DragEvent, idx: number) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    if (dragIndex.current !== idx) {
      setDragOverIdx(idx);
    }
  };

  const handleDragLeave = () => {
    setDragOverIdx(null);
  };

  const handleDrop = (e: React.DragEvent, dropIdx: number) => {
    e.preventDefault();
    setDragOverIdx(null);
    const fromIdx = dragIndex.current;
    if (fromIdx === null || fromIdx === dropIdx) return;
    setWidgets((prev) => {
      const next = [...prev];
      const [moved] = next.splice(fromIdx, 1);
      next.splice(dropIdx, 0, moved);
      return next;
    });
    dragIndex.current = null;
  };

  const handleDragEnd = () => {
    dragIndex.current = null;
    setDragOverIdx(null);
  };

  const SizeIcon = ({ size }: { size: Widget['size'] }) => {
    switch (size) {
      case 'sm': return <Minimize2 className="w-3.5 h-3.5" />;
      case 'md': return <Square className="w-3.5 h-3.5" />;
      case 'lg': return <Maximize2 className="w-3.5 h-3.5" />;
    }
  };

  return (
    <PageLayout>
      <div className="p-3 md:p-6">
        <div className="flex items-center justify-between">
          <PageHeader
            title="위젯 대시보드"
            description="원하는 위젯을 자유롭게 배치하세요."
            icon={LayoutGrid}
          />
          <div className="flex items-center gap-2">
            {editMode && (
              <button onClick={resetWidgets} className="text-xs text-muted-foreground hover:text-foreground px-3 py-1.5 rounded-md hover:bg-muted">
                초기화
              </button>
            )}
            <button
              onClick={() => setEditMode(!editMode)}
              className={`flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-md transition-colors ${editMode ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-muted'}`}
            >
              {editMode ? '완료' : '편집'}
            </button>
            <DashboardSwitcher />
          </div>
        </div>

        <div className="mt-6 grid grid-cols-1 xl:grid-cols-2 gap-4">
          {widgets.map((widget, idx) => (
            <Card
              key={widget.id}
              draggable={editMode}
              onDragStart={editMode ? (e) => handleDragStart(e, idx) : undefined}
              onDragOver={editMode ? (e) => handleDragOver(e, idx) : undefined}
              onDragLeave={editMode ? handleDragLeave : undefined}
              onDrop={editMode ? (e) => handleDrop(e, idx) : undefined}
              onDragEnd={editMode ? handleDragEnd : undefined}
              className={`${sizeClass(widget.size)} transition-all ${
                editMode ? 'ring-2 ring-dashed ring-primary/30' : ''
              } ${editMode && dragIndex.current === idx ? 'opacity-40' : ''} ${
                editMode && dragOverIdx === idx ? 'ring-2 ring-primary ring-solid' : ''
              }`}
            >
              <CardHeader className="flex flex-row items-center justify-between py-3 px-4">
                <div className="flex items-center gap-2">
                  {editMode && <GripVertical className="w-4 h-4 text-muted-foreground cursor-grab" />}
                  <CardTitle className="text-sm font-semibold">{widget.title}</CardTitle>
                </div>
                {editMode && (
                  <div className="flex items-center gap-1">
                    <button onClick={() => toggleSize(widget.id)} className="p-1 rounded hover:bg-muted" title={`크기 변경 (현재: ${widget.size})`}>
                      <SizeIcon size={widget.size} />
                    </button>
                    <button onClick={() => removeWidget(widget.id)} className="p-1 rounded hover:bg-red-50 text-muted-foreground hover:text-red-500" title="삭제">
                      <X className="w-3.5 h-3.5" />
                    </button>
                  </div>
                )}
              </CardHeader>
              <CardContent className="px-4 pb-4">
                {renderWidgetContent(widget.type)}
              </CardContent>
            </Card>
          ))}

          {editMode && (
            <div className="col-span-1 xl:col-span-2">
              {showAddPanel && removedWidgets.length > 0 ? (
                <div className="border-2 border-dashed border-primary/30 rounded-xl p-4">
                  <div className="flex items-center justify-between mb-3">
                    <span className="text-sm font-medium text-muted-foreground">추가할 위젯 선택</span>
                    <button onClick={() => setShowAddPanel(false)} className="p-1 rounded hover:bg-muted">
                      <X className="w-4 h-4 text-muted-foreground" />
                    </button>
                  </div>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                    {removedWidgets.map((w) => (
                      <button
                        key={w.id}
                        onClick={() => addWidget(w)}
                        className="flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 hover:border-primary/40 transition-colors text-left"
                      >
                        <Plus className="w-4 h-4 text-primary flex-shrink-0" />
                        <span className="text-sm">{w.title}</span>
                      </button>
                    ))}
                  </div>
                </div>
              ) : removedWidgets.length > 0 ? (
                <button
                  onClick={() => setShowAddPanel(true)}
                  className="w-full border-2 border-dashed border-muted-foreground/20 rounded-xl flex items-center justify-center py-12 hover:border-primary/40 cursor-pointer transition-colors"
                >
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <Plus className="w-5 h-5" />
                    <span className="text-sm font-medium">위젯 추가</span>
                  </div>
                </button>
              ) : (
                <div className="border rounded-xl flex items-center justify-center py-8 bg-muted/30">
                  <p className="text-sm text-muted-foreground">추가할 수 있는 위젯이 없습니다.</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </PageLayout>
  );
}
