'use client';

import { useState, useEffect, useMemo } from 'react';
import { LayoutDashboard, RefreshCw } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DashboardSwitcher } from '@/components/business/DashboardSwitcher';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { RollingText, type RollingItem } from './RollingText';
import { OverviewTab } from './tabs/OverviewTab';
import { FinanceTab } from './tabs/FinanceTab';
import { SalesTab } from './tabs/SalesTab';
import { ExpenseTab } from './tabs/ExpenseTab';
import { ScheduleTab } from './tabs/ScheduleTab';
import { useDashboardType2, getRollingItems } from './hooks/useDashboardType2';

interface TabConfig {
  value: string;
  label: string;
  badge?: number;
  rollingItems: RollingItem[];
}

export function DashboardType2() {
  const [activeTab, setActiveTab] = useState('schedule');
  const [globalTick, setGlobalTick] = useState(0);

  const data = useDashboardType2();

  useEffect(() => {
    const timer = setInterval(() => {
      setGlobalTick((prev) => prev + 1);
    }, 2500);
    return () => clearInterval(timer);
  }, []);

  const tabs = useMemo<TabConfig[]>(() => [
    {
      value: 'schedule',
      label: '일정/이슈',
      badge: data.schedule.todayItems.length + data.schedule.issueItems.length || undefined,
      rollingItems: getRollingItems('schedule', data),
    },
    {
      value: 'overview',
      label: '전체 요약',
      rollingItems: getRollingItems('overview', data),
    },
    {
      value: 'finance',
      label: '재무 관리',
      rollingItems: getRollingItems('finance', data),
    },
    {
      value: 'sales',
      label: '영업/매출',
      rollingItems: getRollingItems('sales', data),
    },
    {
      value: 'expense',
      label: '경비 관리',
      rollingItems: getRollingItems('expense', data),
    },
  ], [data]);

  const hasError = data.overview.error || data.finance.error || data.sales.error || data.expense.error || data.schedule.error;

  return (
    <PageLayout>
      <div className="p-3 md:p-6">
        <div className="flex items-center justify-between">
          <PageHeader
            title="대시보드"
            description="주요 경영 지표를 한눈에 확인합니다."
            icon={LayoutDashboard}
          />
          <div className="flex items-center gap-2">
            <button
              onClick={data.refetchAll}
              className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors px-3 py-1.5 rounded-md hover:bg-muted"
              title="데이터 새로고침"
            >
              <RefreshCw className="w-4 h-4" />
              <span className="hidden sm:inline">새로고침</span>
            </button>
            <DashboardSwitcher />
          </div>
        </div>

        {hasError && (
          <div className="mt-4 p-3 rounded-lg bg-yellow-50 border border-yellow-200 text-yellow-800 text-sm flex items-center justify-between">
            <span>일부 데이터를 불러오지 못했습니다. 임시 데이터가 표시될 수 있습니다.</span>
            <button
              onClick={data.refetchAll}
              className="text-yellow-700 hover:text-yellow-900 font-medium underline ml-2"
            >
              재시도
            </button>
          </div>
        )}

        <div className="mt-6">
          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="bg-transparent border-b-2 border-border rounded-none w-full gap-0 p-0 h-auto justify-start flex-wrap">
              {tabs.map((tab) => (
                <TabsTrigger
                  key={tab.value}
                  value={tab.value}
                  className="relative flex-1 md:flex-none rounded-none border-b-[3px] border-transparent data-[state=active]:border-primary data-[state=active]:bg-primary/5 data-[state=active]:shadow-none px-2 py-2.5 md:px-5 md:py-4 lg:px-7 lg:py-5 xl:px-8 xl:py-5 text-xs md:text-sm lg:text-base xl:text-lg font-semibold text-muted-foreground data-[state=active]:text-primary whitespace-nowrap transition-colors"
                >
                  <span className="flex items-center gap-1 md:gap-1.5 lg:gap-2">
                    <span>{tab.label}</span>
                    {tab.badge != null && tab.badge > 0 && (
                      <span className="inline-flex items-center justify-center min-w-[18px] h-[18px] md:min-w-[20px] md:h-[20px] lg:min-w-[22px] lg:h-[22px] px-1 rounded-full bg-red-500 text-white text-[10px] md:text-[11px] lg:text-xs font-bold leading-none">
                        {tab.badge}
                      </span>
                    )}
                  </span>
                  <span className={`hidden xl:inline-flex items-center gap-1.5 ml-2 w-[200px] overflow-hidden ${activeTab === tab.value ? 'invisible' : ''}`}>
                    <span className="text-muted-foreground/40 flex-shrink-0">|</span>
                    <span className="flex-1 overflow-hidden"><RollingText items={tab.rollingItems} globalTick={globalTick} /></span>
                  </span>
                </TabsTrigger>
              ))}
            </TabsList>

            <div className="mt-6">
              <TabsContent value="schedule">
                <ScheduleTab data={data.schedule} />
              </TabsContent>
              <TabsContent value="overview">
                <OverviewTab data={data.overview} />
              </TabsContent>
              <TabsContent value="finance">
                <FinanceTab data={data.finance} />
              </TabsContent>
              <TabsContent value="sales">
                <SalesTab data={data.sales} />
              </TabsContent>
              <TabsContent value="expense">
                <ExpenseTab data={data.expense} />
              </TabsContent>
            </div>
          </Tabs>
        </div>
      </div>
    </PageLayout>
  );
}
