'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { FileText, Download, Pencil } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { PageLayout } from '@/components/organisms/PageLayout';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import type { VendorLedgerDetail as VendorLedgerDetailType, TransactionEntry } from './types';

interface VendorLedgerDetailProps {
  vendorId: string;
}

// ===== Mock 데이터 =====
const getMockVendorDetail = (id: string): VendorLedgerDetailType => ({
  id,
  vendorName: '',
  businessNumber: '123-12-12345',
  representativeName: '홍길동',
  phone: '02-1234-1234',
  mobile: '02-1234-1235',
  fax: '02-1234-1236',
  email: 'abc@email.com',
  address: '주소영',
  periodStart: '2025-01-01',
  periodEnd: '2025-12-31',
  transactions: [],
});

const getMockTransactions = (): TransactionEntry[] => [
  {
    id: '1',
    date: '',
    description: '이월잔액',
    salesAmount: 10000000,
    collectionAmount: 0,
    balance: 10000000,
    type: 'carryover',
    hasAction: true,
  },
  {
    id: '2',
    date: '2025-01-01',
    description: '수취 어음 (만기 1/5)',
    salesAmount: 0,
    collectionAmount: 3000000,
    balance: 10000000,
    type: 'note',
    hasAction: false,
    isParenthesis: true, // 괄호 표시
  },
  {
    id: '3',
    date: '2025-01-05',
    description: '어음 (결제 완료)',
    salesAmount: 0,
    collectionAmount: 3000000,
    balance: 7000000,
    type: 'note',
    hasAction: false,
  },
  {
    id: '4',
    date: '',
    description: '2025/01 계',
    salesAmount: 10000000,
    collectionAmount: 3000000,
    balance: 7000000,
    type: 'monthly_total',
    hasAction: false,
  },
  {
    id: '5',
    date: '2025-09-25',
    description: '제품 납품',
    salesAmount: 1000000,
    collectionAmount: 0,
    balance: 1000000,
    type: 'sales',
    hasAction: false,
  },
  {
    id: '6',
    date: '',
    description: '품목명',
    salesAmount: 500000,
    collectionAmount: 0,
    balance: 0,
    type: 'item',
    isHighlighted: true,
    hasAction: false,
  },
  {
    id: '7',
    date: '',
    description: '품목명',
    salesAmount: 500000,
    collectionAmount: 0,
    balance: 0,
    type: 'item',
    isHighlighted: true,
    hasAction: false,
  },
  {
    id: '8',
    date: '',
    description: '2025/09 계',
    salesAmount: 1000000,
    collectionAmount: 0,
    balance: 1000000,
    type: 'monthly_total',
    hasAction: false,
  },
  {
    id: '9',
    date: '',
    description: '총 123건 누계 (VAT 포함)',
    salesAmount: 11000000,
    collectionAmount: 3000000,
    balance: 8000000,
    type: 'subtotal',
    itemCount: 123,
    hasAction: false,
  },
];

export function VendorLedgerDetail({ vendorId }: VendorLedgerDetailProps) {
  const router = useRouter();

  // ===== 상태 관리 =====
  const [startDate, setStartDate] = useState(() => format(new Date(2025, 8, 1), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(() => format(new Date(2025, 8, 3), 'yyyy-MM-dd'));

  // Mock 데이터
  const vendorDetail = useMemo(() => getMockVendorDetail(vendorId), [vendorId]);
  const transactions = useMemo(() => getMockTransactions(), []);

  // ===== 핸들러 =====
  const handleBack = useCallback(() => {
    router.push('/ko/accounting/vendor-ledger');
  }, [router]);

  const handlePdfDownload = useCallback(() => {
    console.log('PDF 다운로드');
  }, []);

  const handleEditTransaction = useCallback((transactionId: string) => {
    // 어음 상세 화면으로 이동
    router.push(`/ko/accounting/bills/${transactionId}`);
  }, [router]);

  // ===== 금액 포맷 =====
  const formatAmount = (amount: number, isParenthesis?: boolean) => {
    if (amount === 0) return '';
    const formatted = amount.toLocaleString();
    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';
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <div className="flex items-center gap-4 mb-6">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-orange-100 rounded-lg">
            <FileText className="h-5 w-5 text-orange-600" />
          </div>
          <div>
            <h1 className="text-xl font-bold">거래처원장 상세 (거래명세서별)</h1>
            <p className="text-sm text-gray-500">거래처 상세 내역을 조회합니다.</p>
          </div>
        </div>
        <Button variant="outline" size="sm" onClick={handleBack}>
          목록
        </Button>
      </div>

      {/* 기간 선택 영역 */}
      <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">
                <span className="text-gray-500 w-28 shrink-0">회사명</span>
                <span className="font-medium">{vendorDetail.vendorName || '-'}</span>
              </div>
              <div className="flex">
                <span className="text-gray-500 w-28 shrink-0">사업자등록번호</span>
                <span>{vendorDetail.businessNumber}</span>
              </div>
              <div className="flex">
                <span className="text-gray-500 w-28 shrink-0">전화번호</span>
                <span>{vendorDetail.phone}</span>
              </div>
              <div className="flex">
                <span className="text-gray-500 w-28 shrink-0">팩스</span>
                <span>{vendorDetail.fax}</span>
              </div>
              <div className="flex">
                <span className="text-gray-500 w-28 shrink-0">주소</span>
                <span>{vendorDetail.address}</span>
              </div>
            </div>

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

      {/* 판매/수금 내역 */}
      <Card>
        <CardContent className="p-0">
          <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.id)}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </PageLayout>
  );
}