'use client';

import { useRouter } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { PageLayout, PageHeader } from '@/components/organisms';
import { FileText } from 'lucide-react';
import { TAX_INVOICE_STATUS_MAP } from './types';
import type {
  TaxInvoiceFormData,
  TaxInvoiceRecord,
  BusinessEntity,
} from './types';

interface TaxInvoiceDetailProps {
  id: string;
  initialData?: TaxInvoiceFormData & {
    id: string;
    invoiceNumber: string;
    status: TaxInvoiceRecord['status'];
  };
}

export function TaxInvoiceDetail({ id, initialData }: TaxInvoiceDetailProps) {
  const router = useRouter();

  const renderEntityInfo = (entity: BusinessEntity, label: string) => (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="text-base">{label}</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-[80px_1fr] gap-y-1.5 gap-x-2 text-sm">
          <span className="text-muted-foreground">사업자번호</span>
          <span>{entity.businessNumber || '-'}</span>
          <span className="text-muted-foreground">상호</span>
          <span>{entity.companyName || '-'}</span>
          <span className="text-muted-foreground">대표자</span>
          <span>{entity.representativeName || '-'}</span>
          <span className="text-muted-foreground">주소</span>
          <span>{entity.address || '-'}</span>
          <span className="text-muted-foreground">업태</span>
          <span>{entity.businessType || '-'}</span>
          <span className="text-muted-foreground">종목</span>
          <span>{entity.businessItem || '-'}</span>
        </div>
      </CardContent>
    </Card>
  );

  if (!initialData) {
    return (
      <PageLayout>
        <PageHeader
          title="세금계산서 상세"
          description="세금계산서 정보를 확인합니다."
          icon={FileText}
        />
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            세금계산서를 찾을 수 없습니다. (ID: {id})
          </CardContent>
        </Card>
        <div className="flex justify-end">
          <Button
            variant="outline"
            onClick={() => router.push('/ko/accounting/tax-invoice-issuance')}
          >
            목록으로
          </Button>
        </div>
      </PageLayout>
    );
  }

  const statusInfo = TAX_INVOICE_STATUS_MAP[initialData.status];
  const totalSupply = initialData.items.reduce((sum, item) => sum + item.supplyAmount, 0);
  const totalTax = initialData.items.reduce((sum, item) => sum + item.taxAmount, 0);
  const totalAmount = initialData.items.reduce((sum, item) => sum + item.totalAmount, 0);

  return (
    <PageLayout>
      <PageHeader
        title="세금계산서 상세"
        description="세금계산서 정보를 확인합니다."
        icon={FileText}
      />

      {/* 기본 정보 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">기본 정보</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <span className="text-muted-foreground block">발행번호</span>
              <span className="font-medium">{initialData.invoiceNumber}</span>
            </div>
            <div>
              <span className="text-muted-foreground block">작성일자</span>
              <span>{initialData.writeDate}</span>
            </div>
            <div>
              <span className="text-muted-foreground block">상태</span>
              <span
                className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${statusInfo.color}`}
              >
                {statusInfo.label}
              </span>
            </div>
            <div>
              <span className="text-muted-foreground block">합계금액</span>
              <span className="font-medium">{totalAmount.toLocaleString('ko-KR')}원</span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 공급자 / 공급받는자 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {renderEntityInfo(initialData.supplier, '공급자')}
        {renderEntityInfo(initialData.receiver, '공급받는자')}
      </div>

      {/* 품목 테이블 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">품목 내역</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[40px] text-center">No.</TableHead>
                  <TableHead className="w-[40px] text-center">월</TableHead>
                  <TableHead className="w-[40px] text-center">일</TableHead>
                  <TableHead className="min-w-[120px]">품목</TableHead>
                  <TableHead className="min-w-[80px]">규격</TableHead>
                  <TableHead className="w-[70px] text-right">수량</TableHead>
                  <TableHead className="w-[90px] text-right">단가</TableHead>
                  <TableHead className="w-[100px] text-right">공급가액</TableHead>
                  <TableHead className="w-[90px] text-right">세액</TableHead>
                  <TableHead className="w-[100px] text-right">합계</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {initialData.items.map((item, index) => (
                  <TableRow key={item.id}>
                    <TableCell className="text-center">{index + 1}</TableCell>
                    <TableCell className="text-center">{item.month || '-'}</TableCell>
                    <TableCell className="text-center">{item.day || '-'}</TableCell>
                    <TableCell>{item.itemName || '-'}</TableCell>
                    <TableCell>{item.specification || '-'}</TableCell>
                    <TableCell className="text-right">{item.quantity.toLocaleString('ko-KR')}</TableCell>
                    <TableCell className="text-right">{item.unitPrice.toLocaleString('ko-KR')}</TableCell>
                    <TableCell className="text-right">{item.supplyAmount.toLocaleString('ko-KR')}</TableCell>
                    <TableCell className="text-right">{item.taxAmount.toLocaleString('ko-KR')}</TableCell>
                    <TableCell className="text-right font-medium">{item.totalAmount.toLocaleString('ko-KR')}</TableCell>
                  </TableRow>
                ))}
                <TableRow className="bg-muted/30 font-medium">
                  <TableCell colSpan={7} className="text-right">합계</TableCell>
                  <TableCell className="text-right">{totalSupply.toLocaleString('ko-KR')}</TableCell>
                  <TableCell className="text-right">{totalTax.toLocaleString('ko-KR')}</TableCell>
                  <TableCell className="text-right">{totalAmount.toLocaleString('ko-KR')}</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 비고 */}
      {initialData.memo && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">비고</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm whitespace-pre-wrap">{initialData.memo}</p>
          </CardContent>
        </Card>
      )}

      {/* 하단 버튼 */}
      <div className="flex justify-end">
        <Button
          variant="outline"
          onClick={() => router.push('/ko/accounting/tax-invoice-issuance')}
        >
          목록으로
        </Button>
      </div>
    </PageLayout>
  );
}
