'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import { format, startOfYear, endOfYear } from 'date-fns';
import { FileText, Loader2, Printer } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { DateRangePicker } from '@/components/ui/date-range-picker';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { printElement } from '@/lib/print-utils';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { PeriodView } from './PeriodView';
import { MonthlyView } from './MonthlyView';
import { getIncomeStatement, getMonthlyIncomeStatement } from './actions';
import type {
  ViewMode,
  UnitType,
  IncomeStatementData,
  IncomeStatementMonthlyData,
} from './types';

const UNIT_OPTIONS: { value: UnitType; label: string }[] = [
  { value: 'won', label: '원' },
  { value: 'thousand', label: '천원' },
  { value: 'million', label: '백만원' },
];

const UNIT_LABEL_MAP: Record<UnitType, string> = {
  won: '원',
  thousand: '천원',
  million: '백만원',
};

export function IncomeStatement() {
  // 보기 모드
  const [viewMode, setViewMode] = useState<ViewMode>('period');
  const [unit, setUnit] = useState<UnitType>('won');

  // 기간 보기 상태
  const [startDate, setStartDate] = useState(() => format(startOfYear(new Date()), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(() => format(new Date(), 'yyyy-MM-dd'));
  const [showPrevious, setShowPrevious] = useState(true);
  const [periodData, setPeriodData] = useState<IncomeStatementData | null>(null);

  // 월별 보기 상태
  const [year, setYear] = useState(() => new Date().getFullYear());
  const [selectedMonth, setSelectedMonth] = useState<string | null>(null); // null = 전체
  const [monthlyData, setMonthlyData] = useState<IncomeStatementMonthlyData | null>(null);

  // 로딩
  const [isLoading, setIsLoading] = useState(false);

  // 연도 옵션 (2025 ~ 현재 연도)
  const yearOptions = Array.from(
    { length: new Date().getFullYear() - 2024 },
    (_, i) => 2025 + i
  );

  // 기간 보기 데이터 로드
  const loadPeriodData = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getIncomeStatement({ startDate, endDate, unit });
      if (result.success && result.data) {
        setPeriodData(result.data);
      } else {
        toast.error(result.error || '손익계산서 조회에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('손익계산서 조회 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [startDate, endDate, unit]);

  // 월별 보기 데이터 로드
  const loadMonthlyData = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getMonthlyIncomeStatement({ year, unit });
      if (result.success && result.data) {
        setMonthlyData(result.data);
      } else {
        toast.error(result.error || '월별 손익계산서 조회에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('월별 손익계산서 조회 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [year, unit]);

  // 데이터 로드 트리거
  useEffect(() => {
    if (viewMode === 'period') {
      loadPeriodData();
    } else {
      loadMonthlyData();
    }
  }, [viewMode, loadPeriodData, loadMonthlyData]);

  // 인쇄
  const printAreaRef = useRef<HTMLDivElement>(null);
  const handlePrint = useCallback(() => {
    if (printAreaRef.current) {
      printElement(printAreaRef.current, {
        title: viewMode === 'period'
          ? `손익계산서_${startDate}_${endDate}`
          : `손익계산서_${year}년_월별`,
        styles: `
          .print-container { font-size: 11px; }
          table { width: 100%; }
          .bg-green-50 { background-color: #f0fdf4 !important; -webkit-print-color-adjust: exact; }
          .bg-muted\\/30 { background-color: #f5f5f5 !important; -webkit-print-color-adjust: exact; }
        `,
      });
    }
  }, [viewMode, startDate, endDate, year]);

  // 월 선택 버튼 (월별 보기용)
  const availableMonths = monthlyData?.months.map((m) => m.month) || [];

  return (
    <PageLayout>
      <PageHeader
        title="손익계산서"
        description="기간별/월별 손익계산서를 조회합니다."
        icon={FileText}
      />

      {/* 필터 영역 */}
      <Card>
        <CardContent className="p-3 md:p-4">
          <div className="flex flex-col gap-3">
            {/* 1행: 보기 모드 + 단위 | 인쇄 */}
            <div className="flex items-center justify-between gap-2">
              <div className="flex items-center gap-2">
                <Tabs
                  value={viewMode}
                  onValueChange={(v) => setViewMode(v as ViewMode)}
                >
                  <TabsList className="h-8">
                    <TabsTrigger value="period" className="text-xs px-3 h-7">
                      기간 보기
                    </TabsTrigger>
                    <TabsTrigger value="monthly" className="text-xs px-3 h-7">
                      월별 보기
                    </TabsTrigger>
                  </TabsList>
                </Tabs>
                <Select value={unit} onValueChange={(v) => setUnit(v as UnitType)}>
                  <SelectTrigger className="h-8 w-[80px] text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {UNIT_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value} className="text-xs">
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={handlePrint}
                className="h-8 px-3 text-xs shrink-0"
              >
                <Printer className="mr-1 h-3.5 w-3.5" />
                인쇄
              </Button>
            </div>

            {/* 2행: 모드별 필터 */}
            {viewMode === 'period' ? (
              <div className="flex flex-col sm:flex-row sm:items-center gap-2">
                <DateRangePicker
                  startDate={startDate}
                  endDate={endDate}
                  onStartDateChange={setStartDate}
                  onEndDateChange={setEndDate}
                  size="sm"
                  className="w-full sm:w-auto sm:min-w-[280px]"
/>
                <div className="flex items-center gap-1.5">
                  <Button
                    variant={showPrevious ? 'default' : 'outline'}
                    size="sm"
                    className="h-7 px-2.5 text-xs"
                    onClick={() => setShowPrevious(true)}
                  >
                    당기+전기
                  </Button>
                  <Button
                    variant={!showPrevious ? 'default' : 'outline'}
                    size="sm"
                    className="h-7 px-2.5 text-xs"
                    onClick={() => setShowPrevious(false)}
                  >
                    당기만
                  </Button>
                </div>
              </div>
            ) : (
              <div className="flex flex-col gap-2">
                <div className="flex items-center gap-2">
                  <Select
                    value={String(year)}
                    onValueChange={(v) => setYear(Number(v))}
                  >
                    <SelectTrigger className="h-8 w-[100px] text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {yearOptions.map((y) => (
                        <SelectItem key={y} value={String(y)} className="text-xs">
                          {y}년
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex items-center gap-1.5 overflow-x-auto pb-1 -mb-1">
                  <Button
                    variant={selectedMonth === null ? 'default' : 'outline'}
                    size="sm"
                    className="h-7 px-2.5 text-xs shrink-0"
                    onClick={() => setSelectedMonth(null)}
                  >
                    전체
                  </Button>
                  {Array.from({ length: 12 }, (_, i) => {
                    const m = String(i + 1).padStart(2, '0');
                    const isAvailable = availableMonths.includes(m);
                    return (
                      <Button
                        key={m}
                        variant={selectedMonth === m ? 'default' : 'outline'}
                        size="sm"
                        className="h-7 px-2 text-xs shrink-0"
                        onClick={() => setSelectedMonth(m)}
                        disabled={!isAvailable}
                      >
                        {i + 1}월
                      </Button>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 데이터 영역 */}
      <div ref={printAreaRef}>
        {isLoading ? (
          <Card>
            <CardContent className="py-16">
              <div className="flex items-center justify-center gap-2">
                <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
                <span className="text-gray-500 text-sm">데이터를 불러오는 중...</span>
              </div>
            </CardContent>
          </Card>
        ) : viewMode === 'period' && periodData ? (
          <Card>
            <CardContent className="px-3 pt-4 pb-3 md:px-6 md:pt-6 md:pb-4">
              <PeriodView
                data={periodData}
                showPrevious={showPrevious}
                unitLabel={UNIT_LABEL_MAP[unit]}
              />
            </CardContent>
          </Card>
        ) : viewMode === 'monthly' && monthlyData ? (
          <Card>
            <CardContent className="px-3 pt-4 pb-3 md:px-6 md:pt-6 md:pb-4">
              <MonthlyView
                data={monthlyData}
                selectedMonth={selectedMonth}
                unitLabel={UNIT_LABEL_MAP[unit]}
              />
            </CardContent>
          </Card>
        ) : !isLoading ? (
          <Card>
            <CardContent className="py-16 text-center text-muted-foreground text-sm">
              데이터가 없습니다.
            </CardContent>
          </Card>
        ) : null}
      </div>
    </PageLayout>
  );
}
