import React, { useState } from 'react';
import { ListPageTemplate } from './templates/ListPageTemplate';
import { Column } from './organisms/DataTable';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './ui/dialog';
import { TaxInvoice } from './TaxInvoice';
import {
  ShoppingCart,
  FileText,
  TrendingDown,
  Package,
  Clock,
  Eye,
  Printer,
  Download
} from 'lucide-react';

interface PurchaseData {
  id: string;
  poNo: string;
  invoiceDate: string;
  supplier: string;
  material: string;
  quantity: number;
  unitPrice: number;
  totalAmount: number;
  vat: number;
  totalWithVat: number;
  status: string;
  paymentDue: string;
  paymentStatus: string;
  buyer: string;
}

export function PurchaseAccountingManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedPeriod, setSelectedPeriod] = useState('전체');
  const [selectedStatus, setSelectedStatus] = useState('전체');
  const [isInvoiceModalOpen, setIsInvoiceModalOpen] = useState(false);
  const [selectedInvoiceData, setSelectedInvoiceData] = useState<any>(null);

  // 매입 데이터 (구매관리, 입고관리 데이터와 연동)
  const purchaseData: PurchaseData[] = [
    {
      id: 'PUR-2025-001',
      poNo: 'PO-2025-001',
      invoiceDate: '2025-03-10',
      supplier: '(주)알루미늄공업',
      material: '알루미늄 프로파일',
      quantity: 500,
      unitPrice: 25000,
      totalAmount: 12500000,
      vat: 1250000,
      totalWithVat: 13750000,
      status: '세금계산서 수령',
      paymentDue: '2025-04-10',
      paymentStatus: '미지급',
      buyer: '박민수'
    },
    {
      id: 'PUR-2025-002',
      poNo: 'PO-2025-002',
      invoiceDate: '2025-03-12',
      supplier: '대한패브릭',
      material: '패브릭 원단',
      quantity: 200,
      unitPrice: 35000,
      totalAmount: 7000000,
      vat: 700000,
      totalWithVat: 7700000,
      status: '세금계산서 수령',
      paymentDue: '2025-04-12',
      paymentStatus: '완료',
      buyer: '박민수'
    },
    {
      id: 'PUR-2025-003',
      poNo: 'PO-2025-003',
      invoiceDate: '2025-03-15',
      supplier: '모터산업',
      material: '자동 모터',
      quantity: 100,
      unitPrice: 85000,
      totalAmount: 8500000,
      vat: 850000,
      totalWithVat: 9350000,
      status: '입고 완료',
      paymentDue: '2025-04-15',
      paymentStatus: '미지급',
      buyer: '김철수'
    },
    {
      id: 'PUR-2025-004',
      poNo: 'PO-2025-004',
      invoiceDate: '2025-03-18',
      supplier: '볼트너트',
      material: '볼트/너트 세트',
      quantity: 1000,
      unitPrice: 5000,
      totalAmount: 5000000,
      vat: 500000,
      totalWithVat: 5500000,
      status: '세금계산서 수령',
      paymentDue: '2025-04-18',
      paymentStatus: '미지급',
      buyer: '박민수'
    },
    {
      id: 'PUR-2025-005',
      poNo: 'PO-2025-005',
      invoiceDate: '2025-03-22',
      supplier: '철강유통',
      material: '철판 1.2T',
      quantity: 300,
      unitPrice: 45000,
      totalAmount: 13500000,
      vat: 1350000,
      totalWithVat: 14850000,
      status: '세금계산서 수령',
      paymentDue: '2025-04-22',
      paymentStatus: '완료',
      buyer: '김철수'
    },
  ];

  const periods = ['전체', '당월', '전월', '당분기', '당년'];
  const statuses = ['전체', '입고 완료', '세금계산서 수령', '지급 완료'];

  const filteredPurchases = purchaseData.filter(purchase => {
    const matchesSearch = purchase.poNo.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         purchase.supplier.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         purchase.material.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = selectedStatus === '전체' || purchase.status === selectedStatus;
    return matchesSearch && matchesStatus;
  });

  const totalPurchase = filteredPurchases.reduce((sum, purchase) => sum + purchase.totalAmount, 0);
  const totalVat = filteredPurchases.reduce((sum, purchase) => sum + purchase.vat, 0);
  const totalWithVat = filteredPurchases.reduce((sum, purchase) => sum + purchase.totalWithVat, 0);
  const unpaidAmount = filteredPurchases.filter(p => p.paymentStatus === '미지급').reduce((sum, purchase) => sum + purchase.totalWithVat, 0);

  const formatCurrency = (amount: number) => {
    return amount.toLocaleString('ko-KR') + '원';
  };

  // 세금계산서 데이터 생성 (매입용)
  const generateTaxInvoiceData = (purchase: PurchaseData) => {
    return {
      invoiceNo: purchase.id,
      issueDate: purchase.invoiceDate,
      supplier: {
        companyName: purchase.supplier,
        businessNo: '234-56-78901',
        representative: '이대표',
        address: '경기도 시흥시 공단로 123',
        businessType: '제조업',
        businessItem: '자재 제조',
        phone: '031-1234-5678',
        email: `${purchase.supplier.toLowerCase().replace(/[\s()]/g, '')}@company.com`
      },
      recipient: {
        companyName: '(주)SAM 시스템',
        businessNo: '123-45-67890',
        representative: '홍길동',
        address: '서울특별시 강남구 테헤란로 123',
        businessType: '제조업',
        businessItem: '블라인드 제조',
        phone: '02-1234-5678',
        email: 'sam@company.com'
      },
      items: [
        {
          date: purchase.invoiceDate.slice(5),
          item: purchase.material,
          spec: '표준',
          quantity: purchase.quantity,
          unit: 'EA',
          unitPrice: purchase.unitPrice,
          supplyAmount: purchase.totalAmount,
          tax: purchase.vat,
          note: purchase.poNo
        }
      ],
      totalSupplyAmount: purchase.totalAmount,
      totalTax: purchase.vat,
      totalAmount: purchase.totalWithVat,
      note: `발주번호: ${purchase.poNo} / 담당자: ${purchase.buyer}`,
      type: 'purchase' as const
    };
  };

  // 세금계산서 미리보기
  const handleViewInvoice = (purchase: PurchaseData) => {
    const invoiceData = generateTaxInvoiceData(purchase);
    setSelectedInvoiceData(invoiceData);
    setIsInvoiceModalOpen(true);
  };

  const columns: Column<PurchaseData>[] = [
    {
      key: 'invoiceDate',
      label: '계산서일자'
    },
    {
      key: 'poNo',
      label: '발주번호'
    },
    {
      key: 'supplier',
      label: '공급업체'
    },
    {
      key: 'material',
      label: '자재명'
    },
    {
      key: 'quantity',
      label: '수량',
      render: (value) => `${(value as number).toLocaleString()}EA`
    },
    {
      key: 'totalAmount',
      label: '공급가액',
      render: (value) => formatCurrency(value as number)
    },
    {
      key: 'vat',
      label: '부가세',
      render: (value) => formatCurrency(value as number)
    },
    {
      key: 'totalWithVat',
      label: '합계금액',
      render: (value) => (
        <span className="font-semibold">
          {formatCurrency(value as number)}
        </span>
      )
    },
    {
      key: 'status',
      label: '상태',
      render: (value) => {
        const status = value as string;
        const variant = status === '지급 완료' ? 'default' : status === '세금계산서 수령' ? 'secondary' : 'outline';
        return <Badge variant={variant}>{status}</Badge>;
      }
    },
    {
      key: 'paymentStatus',
      label: '지급',
      render: (value) => {
        const status = value as string;
        const variant = status === '완료' ? 'default' : 'secondary';
        return <Badge variant={variant}>{status}</Badge>;
      }
    },
    {
      key: 'actions',
      label: '세금계산서',
      render: (_, row) => (
        <Button 
          size="sm" 
          variant="outline"
          onClick={() => handleViewInvoice(row)}
        >
          <Eye className="w-4 h-4 mr-1" />
          보기
        </Button>
      )
    }
  ];

  return (
    <>
      <ListPageTemplate
        title="매입 목록"
        description="구매 및 입고 데이터 기반 매입 현황을 관리합니다"
        icon={ShoppingCart}
        stats={[
          {
            label: "총 매입액",
            value: formatCurrency(totalPurchase),
            icon: ShoppingCart,
            iconColor: "text-blue-600",
            description: "공급가액"
          },
          {
            label: "부가세",
            value: formatCurrency(totalVat),
            icon: TrendingDown,
            iconColor: "text-green-600",
            description: "10%"
          },
          {
            label: "합계금액",
            value: formatCurrency(totalWithVat),
            icon: FileText,
            iconColor: "text-purple-600",
            description: "VAT 포함"
          },
          {
            label: "미지급금",
            value: formatCurrency(unpaidAmount),
            icon: Clock,
            iconColor: "text-orange-600",
            description: "미지급"
          }
        ]}
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="발주번호, 공급업체, 자재명 검색..."
        extraActions={
          <>
            <Select value={selectedPeriod} onValueChange={setSelectedPeriod}>
              <SelectTrigger className="w-[120px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {periods.map(period => (
                  <SelectItem key={period} value={period}>{period}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={selectedStatus} onValueChange={setSelectedStatus}>
              <SelectTrigger className="w-[180px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {statuses.map(status => (
                  <SelectItem key={status} value={status}>{status}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </>
        }
        data={filteredPurchases}
        keyField="id"
        columns={columns}
        renderMobileCard={(purchase) => ({
          title: purchase.supplier,
          subtitle: `${purchase.poNo} | ${purchase.invoiceDate}`,
          badge: {
            label: purchase.status,
            variant: purchase.status === '지급 완료' ? 'default' : 'secondary'
          },
          fields: [
            {
              label: "자재",
              value: purchase.material
            },
            {
              label: "수량",
              value: `${purchase.quantity.toLocaleString()}EA`
            },
            {
              label: "공급가액",
              value: formatCurrency(purchase.totalAmount)
            },
            {
              label: "합계금액",
              value: formatCurrency(purchase.totalWithVat),
              className: "font-semibold"
            },
            {
              label: "지급상태",
              value: purchase.paymentStatus
            },
            {
              label: "담당자",
              value: purchase.buyer
            }
          ],
          actions: [
            {
              label: "세금계산서",
              icon: Eye,
              onClick: () => handleViewInvoice(purchase)
            }
          ]
        })}
        emptyIcon={ShoppingCart}
        emptyTitle="매입 정보가 없습니다"
        emptyDescription="매입 데이터를 등록해주세요"
      />

      {/* 세금계산서 미리보기 다이얼로그 */}
      <Dialog open={isInvoiceModalOpen} onOpenChange={setIsInvoiceModalOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center justify-between">
              <span>세금계산서</span>
              <div className="flex gap-2">
                <Button size="sm" variant="outline" onClick={() => window.print()}>
                  <Printer className="w-4 h-4 mr-1" />
                  인쇄
                </Button>
                <Button size="sm" variant="outline" onClick={() => window.print()}>
                  <Download className="w-4 h-4 mr-1" />
                  다운로드
                </Button>
              </div>
            </DialogTitle>
            <DialogDescription>
              세금계산서를 미리보거나 인쇄, 다운로드할 수 있습니다.
            </DialogDescription>
          </DialogHeader>
          {selectedInvoiceData && (
            <TaxInvoice {...selectedInvoiceData} />
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}