'use client';

import { useState, useEffect } from 'react';
import { ExternalLink, Loader2, CreditCard } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { formatNumber } from '@/lib/utils/amount';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableFooter,
} from '@/components/ui/table';
import { getJournalEntryDetail } from './actions';
import type { LedgerItem, JournalEntryDetail } from './types';
import { formatLedgerAmount, maskCardNumber } from './types';

interface JournalDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  item: LedgerItem | null;
}

const SOURCE_TYPE_LABELS: Record<string, string> = {
  journal: '수기전표',
  ecard_transaction: '카드거래',
  bank_transaction: '은행거래',
  hometax: '홈택스',
};

const STATUS_LABELS: Record<string, string> = {
  draft: '임시',
  confirmed: '확정',
};

export function JournalDetailModal({ open, onOpenChange, item }: JournalDetailModalProps) {
  const router = useRouter();
  const [detail, setDetail] = useState<JournalEntryDetail | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (open && item?.source_id) {
      setIsLoading(true);
      setDetail(null);
      getJournalEntryDetail(item.source_id)
        .then((result) => {
          if (result.success && result.data) {
            setDetail(result.data);
          }
        })
        .finally(() => setIsLoading(false));
    }
  }, [open, item?.source_id]);

  const handleGoToOriginal = () => {
    onOpenChange(false);
    router.push('/accounting/general-journal-entry');
  };

  const totalDebit = detail?.lines?.reduce((sum, l) => sum + l.debit_amount, 0) ?? 0;
  const totalCredit = detail?.lines?.reduce((sum, l) => sum + l.credit_amount, 0) ?? 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <DialogTitle className="text-lg">
              전표 상세
              {detail?.entry_no && (
                <span className="ml-2 text-sm font-normal text-muted-foreground">
                  {detail.entry_no}
                </span>
              )}
            </DialogTitle>
            <Button
              variant="outline"
              size="sm"
              onClick={handleGoToOriginal}
              className="mr-6"
            >
              <ExternalLink className="h-3.5 w-3.5 mr-1" />
              원본 보기
            </Button>
          </div>
        </DialogHeader>

        {isLoading && (
          <div className="py-12 text-center">
            <Loader2 className="h-6 w-6 mx-auto animate-spin text-muted-foreground" />
          </div>
        )}

        {!isLoading && detail && (
          <div className="space-y-4">
            {/* 전표 요약 */}
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm">
              <InfoItem label="전표번호" value={detail.entry_no} />
              <InfoItem label="일자" value={detail.entry_date} />
              <InfoItem label="적요" value={detail.description || '-'} />
              <InfoItem label="작성자" value={detail.created_by_name || '-'} />
              <InfoItem
                label="상태"
                value={STATUS_LABELS[detail.status] || detail.status}
              />
              <InfoItem
                label="출처"
                value={SOURCE_TYPE_LABELS[detail.source_type || ''] || detail.source_type || '-'}
              />
            </div>

            {/* 카드 정보 (card_tx가 있을 때) */}
            {item?.card_tx && (
              <div className="border rounded-lg p-3 bg-blue-50/50">
                <div className="flex items-center gap-1.5 mb-2">
                  <CreditCard className="h-4 w-4 text-blue-600" />
                  <span className="text-sm font-medium">카드 거래 정보</span>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm">
                  <InfoItem
                    label="카드번호"
                    value={`${item.card_tx.card_company_name} ${maskCardNumber(item.card_tx.card_num)}`}
                  />
                  <InfoItem label="가맹점" value={item.card_tx.merchant_name} />
                  <InfoItem label="사업자번호" value={item.card_tx.merchant_biz_num} />
                  <InfoItem
                    label="공급가액"
                    value={formatNumber(item.card_tx.supply_amount)}
                  />
                  <InfoItem
                    label="세액"
                    value={formatNumber(item.card_tx.tax_amount)}
                  />
                  <div>
                    <span className="text-muted-foreground">공제여부</span>
                    <div className="mt-0.5">
                      {item.card_tx.deduction_type === 'deductible' ? (
                        <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                          공제
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">
                          불공제
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* 분개 테이블 */}
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[40px]">No</TableHead>
                    <TableHead className="w-[50px]">구분</TableHead>
                    <TableHead className="w-[80px]">계정코드</TableHead>
                    <TableHead>계정명</TableHead>
                    <TableHead>거래처</TableHead>
                    <TableHead className="text-right w-[110px]">차변</TableHead>
                    <TableHead className="text-right w-[110px]">대변</TableHead>
                    <TableHead>적요</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {detail.lines?.map((line, idx) => (
                    <TableRow key={idx}>
                      <TableCell className="text-sm">{idx + 1}</TableCell>
                      <TableCell>
                        <Badge
                          variant="outline"
                          className={
                            line.dc_type === 'debit'
                              ? 'bg-blue-50 text-blue-700 border-blue-200'
                              : 'bg-orange-50 text-orange-700 border-orange-200'
                          }
                        >
                          {line.dc_type === 'debit' ? '차변' : '대변'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm font-mono">{line.account_code}</TableCell>
                      <TableCell className="text-sm">{line.account_name}</TableCell>
                      <TableCell className="text-sm">{line.trading_partner_name || ''}</TableCell>
                      <TableCell className="text-right text-sm tabular-nums">
                        {formatLedgerAmount(line.debit_amount)}
                      </TableCell>
                      <TableCell className="text-right text-sm tabular-nums">
                        {formatLedgerAmount(line.credit_amount)}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {line.description || ''}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
                <TableFooter>
                  <TableRow className="font-semibold">
                    <TableCell colSpan={5} className="text-right">
                      합계
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {formatLedgerAmount(totalDebit)}
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {formatLedgerAmount(totalCredit)}
                    </TableCell>
                    <TableCell />
                  </TableRow>
                </TableFooter>
              </Table>
            </div>
          </div>
        )}

        {!isLoading && !detail && open && (
          <div className="py-12 text-center text-muted-foreground">
            전표 정보를 불러올 수 없습니다.
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

function InfoItem({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <span className="text-muted-foreground">{label}</span>
      <p className="font-medium mt-0.5">{value}</p>
    </div>
  );
}
