'use client';

/**
 * 거래처원장 상세 페이지
 * IntegratedDetailTemplate 마이그레이션 완료 (2026-01-20)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import { Download, Edit } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ContentSkeleton } from '@/components/ui/skeleton';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { vendorLedgerConfig } from './vendorLedgerConfig';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import type { VendorLedgerDetail as VendorLedgerDetailType, TransactionEntry, VendorLedgerSummary } from './types';
import { getVendorLedgerDetail, exportVendorLedgerDetailPdf } from './actions';
import { formatNumber } from '@/lib/utils/amount';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

interface VendorLedgerDetailProps {
  vendorId: string;
  initialData?: VendorLedgerDetailType;
  initialSummary?: VendorLedgerSummary;
}

export function VendorLedgerDetail({
  vendorId,
  initialData,
  initialSummary,
}: VendorLedgerDetailProps) {
  const router = useRouter();
  const searchParams = useSearchParams();

  // URL에서 초기 날짜 가져오기
  const initialStartDate = searchParams.get('start_date') || format(startOfMonth(new Date()), 'yyyy-MM-dd');
  const initialEndDate = searchParams.get('end_date') || format(endOfMonth(new Date()), 'yyyy-MM-dd');

  // ===== 상태 관리 =====
  const [startDate, setStartDate] = useState(initialStartDate);
  const [endDate, setEndDate] = useState(initialEndDate);
  const [isLoading, setIsLoading] = useState(!initialData);

  // 데이터 상태
  const [vendorDetail, setVendorDetail] = useState<VendorLedgerDetailType | null>(
    initialData || null
  );
  const [summary, setSummary] = useState<VendorLedgerSummary | null>(
    initialSummary || null
  );

  // ===== 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getVendorLedgerDetail(vendorId, {
        startDate,
        endDate,
      });

      if (result.success && result.data) {
        setVendorDetail(result.data);
        if (result.summary) {
          setSummary(result.summary);
        }
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[VendorLedgerDetail] loadData error:', error);
    } finally {
      setIsLoading(false);
    }
  }, [vendorId, startDate, endDate]);

  // 데이터 로드
  useEffect(() => {
    loadData();
  }, [loadData]);

  // ===== 핸들러 =====
  const handlePdfDownload = useCallback(async () => {
    const result = await exportVendorLedgerDetailPdf(vendorId, {
      startDate,
      endDate,
    });

    if (result.success && result.data) {
      const url = URL.createObjectURL(result.data);
      const a = document.createElement('a');
      a.href = url;
      a.download = result.filename || `거래처원장_${vendorId}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      toast.success('PDF 파일이 다운로드되었습니다.');
    } else {
      toast.error(result.error || 'PDF 다운로드에 실패했습니다.');
    }
  }, [vendorId, startDate, endDate]);

  const handleEditTransaction = useCallback((entry: TransactionEntry) => {
    // 어음 관련 항목일 경우 어음 상세로 이동
    if (entry.type === 'note' && entry.noteInfo) {
      router.push(`/ko/accounting/bills/${entry.id}?mode=view`);
    }
  }, [router]);

  // ===== 금액 포맷 =====
  const formatAmount = (amount: number, isParenthesis?: boolean) => {
    if (amount === 0) return '';
    const formatted = formatNumber(amount);
    return isParenthesis ? `(${formatted})` : formatted;
  };

  // ===== 행 스타일 결정 =====
  const getRowStyle = (entry: TransactionEntry) => {
    if (entry.type === 'monthly_total' || entry.type === 'subtotal') {
      return 'bg-gray-100 font-medium';
    }
    return 'bg-white';
  };

  // 거래 내역
  const transactions = useMemo(() => {
    if (!vendorDetail?.transactions) return [];
    return vendorDetail.transactions;
  }, [vendorDetail]);

  // 커스텀 헤더 액션 (PDF 다운로드 버튼)
  const customHeaderActions = useMemo(() => {
    return (
      <Button
        variant="outline"
        size="sm"
        onClick={handlePdfDownload}
      >
        <Download className="h-4 w-4 md:mr-2" />
        <span className="hidden md:inline">PDF 다운로드</span>
      </Button>
    );
  }, [handlePdfDownload]);

  // 폼 콘텐츠 렌더링
  const renderFormContent = useCallback(() => {
    // 로딩 상태 표시
    if (isLoading && !vendorDetail) {
      return <ContentSkeleton type="detail" rows={6} />;
    }

    // 데이터 없음
    if (!vendorDetail) {
      return (
        <div className="flex flex-col items-center justify-center h-64">
          <p className="text-gray-500 mb-4">거래처 정보를 찾을 수 없습니다.</p>
        </div>
      );
    }

    return (
      <div className="space-y-6">
        {/* 기간 선택 영역 */}
      <div className="mb-6">
        <DateRangeSelector
          startDate={startDate}
          endDate={endDate}
          onStartDateChange={setStartDate}
          onEndDateChange={setEndDate}
          extraActions={
            <Button
              variant="outline"
              size="sm"
              onClick={handlePdfDownload}
            >
              <Download className="mr-2 h-4 w-4" />
              PDF 다운로드
            </Button>
          }
        />
      </div>

      {/* 거래처 정보 */}
      <Card className="mb-6">
        <CardContent className="p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-3">
            {/* 좌측 열 */}
            <div className="space-y-3">
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">회사명</span>
                <span className="font-medium">{vendorDetail.vendorName || '-'}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">사업자등록번호</span>
                <span>{vendorDetail.businessNumber || '-'}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">전화번호</span>
                <span>{vendorDetail.phone || '-'}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">팩스</span>
                <span>{vendorDetail.fax || '-'}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">주소</span>
                <span>{vendorDetail.address || '-'}</span>
              </div>
            </div>

            {/* 우측 열 */}
            <div className="space-y-3">
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">기간</span>
                <span>{vendorDetail.periodStart || startDate} ~ {vendorDetail.periodEnd || endDate}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">대표자</span>
                <span>{vendorDetail.representativeName || '-'}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">모바일</span>
                <span>{vendorDetail.mobile || '-'}</span>
              </div>
              <div className="flex flex-col sm:flex-row">
                <span className="text-gray-500 sm:w-28 sm:shrink-0 text-sm">이메일</span>
                <span>{vendorDetail.email || '-'}</span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 요약 통계 */}
      {summary && (
        <Card className="mb-6">
          <CardContent className="p-4">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
              <div>
                <div className="text-sm text-gray-500">이월잔액</div>
                <div className="font-medium">{formatNumber(summary.carryoverBalance)}원</div>
              </div>
              <div>
                <div className="text-sm text-gray-500">매출</div>
                <div className="font-medium text-green-600">{formatNumber(summary.totalSales)}원</div>
              </div>
              <div>
                <div className="text-sm text-gray-500">수금</div>
                <div className="font-medium text-blue-600">{formatNumber(summary.totalCollection)}원</div>
              </div>
              <div>
                <div className="text-sm text-gray-500">잔액</div>
                <div className={`font-medium ${summary.balance < 0 ? 'text-red-600' : ''}`}>
                  {formatNumber(summary.balance)}원
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 판매/수금 내역 */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <ContentSkeleton type="table" rows={5} />
          ) : transactions.length === 0 ? (
            <div className="flex items-center justify-center h-32 text-gray-500">
              거래 내역이 없습니다.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-50 border-b">
                  <TableHead colSpan={5} className="text-center font-bold py-4">
                    판매/수금 내역
                  </TableHead>
                  <TableHead className="text-center w-[80px]">작업</TableHead>
                </TableRow>
                <TableRow className="bg-gray-50">
                  <TableHead className="w-[140px]">일자</TableHead>
                  <TableHead>적요</TableHead>
                  <TableHead className="text-right w-[140px]">판매</TableHead>
                  <TableHead className="text-right w-[140px]">수금</TableHead>
                  <TableHead className="text-right w-[140px]">잔액</TableHead>
                  <TableHead className="text-center w-[80px]"></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {transactions.map((entry) => (
                  <TableRow key={entry.id} className={getRowStyle(entry)}>
                    {/* 일자 */}
                    <TableCell>
                      {entry.date || ''}
                    </TableCell>

                    {/* 적요 */}
                    <TableCell>
                      {entry.type === 'item' ? (
                        <span className="ml-8">{entry.description}</span>
                      ) : (
                        entry.description
                      )}
                    </TableCell>

                    {/* 판매 */}
                    <TableCell className="text-right">
                      {entry.isHighlighted ? (
                        <span className="bg-orange-100 px-2 py-0.5">
                          {formatAmount(entry.salesAmount)}
                        </span>
                      ) : (
                        formatAmount(entry.salesAmount)
                      )}
                    </TableCell>

                    {/* 수금 */}
                    <TableCell className="text-right">
                      {formatAmount(entry.collectionAmount, entry.isParenthesis)}
                    </TableCell>

                    {/* 잔액 */}
                    <TableCell className="text-right">
                      {formatAmount(entry.balance)}
                    </TableCell>

                    {/* 작업 */}
                    <TableCell className="text-center">
                      {entry.hasAction && (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          onClick={() => handleEditTransaction(entry)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
      </div>
    );
  }, [
    isLoading,
    vendorDetail,
    summary,
    transactions,
    startDate,
    endDate,
    setStartDate,
    setEndDate,
    handlePdfDownload,
    handleEditTransaction,
    formatAmount,
    getRowStyle,
  ]);

  return (
    <IntegratedDetailTemplate
      config={vendorLedgerConfig}
      mode="view"
      initialData={(vendorDetail || {}) as Record<string, unknown>}
      itemId={vendorId}
      isLoading={isLoading && !vendorDetail}
      headerActions={customHeaderActions}
      renderView={() => renderFormContent()}
      renderForm={() => renderFormContent()}
    />
  );
}
