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 {
  DollarSign,
  FileText,
  TrendingUp,
  CheckCircle,
  Clock,
  Eye,
  Printer,
  Download
} from 'lucide-react';

interface SalesData {
  id: string;
  orderNo: string;
  invoiceDate: string;
  customer: string;
  product: string;
  quantity: number;
  unitPrice: number;
  totalAmount: number;
  vat: number;
  totalWithVat: number;
  status: string;
  paymentDue: string;
  paymentStatus: string;
  salesperson: string;
}

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

  // 매출 데이터 (수주관리, 출하관리 데이터와 연동)
  const salesData: SalesData[] = [
    {
      id: 'SAL-2025-001',
      orderNo: 'ORD-2025-001',
      invoiceDate: '2025-03-15',
      customer: '삼성전자',
      product: '스크린 기본형',
      quantity: 100,
      unitPrice: 150000,
      totalAmount: 15000000,
      vat: 1500000,
      totalWithVat: 16500000,
      status: '세금계산서 발행',
      paymentDue: '2025-04-15',
      paymentStatus: '미수',
      salesperson: '정수진'
    },
    {
      id: 'SAL-2025-002',
      orderNo: 'ORD-2025-002',
      invoiceDate: '2025-03-18',
      customer: 'LG전자',
      product: '슬랫 표준형',
      quantity: 50,
      unitPrice: 200000,
      totalAmount: 10000000,
      vat: 1000000,
      totalWithVat: 11000000,
      status: '세금계산서 발행',
      paymentDue: '2025-04-18',
      paymentStatus: '완료',
      salesperson: '김철수'
    },
    {
      id: 'SAL-2025-003',
      orderNo: 'ORD-2025-003',
      invoiceDate: '2025-03-20',
      customer: '현대자동차',
      product: '절곡 제품',
      quantity: 75,
      unitPrice: 180000,
      totalAmount: 13500000,
      vat: 1350000,
      totalWithVat: 14850000,
      status: '출하 완료',
      paymentDue: '2025-04-20',
      paymentStatus: '미수',
      salesperson: '박민수'
    },
    {
      id: 'SAL-2025-004',
      orderNo: 'ORD-2025-004',
      invoiceDate: '2025-03-25',
      customer: 'SK하이닉스',
      product: '스크린 프리미엄',
      quantity: 120,
      unitPrice: 220000,
      totalAmount: 26400000,
      vat: 2640000,
      totalWithVat: 29040000,
      status: '세금계산서 발행',
      paymentDue: '2025-04-25',
      paymentStatus: '미수',
      salesperson: '정수진'
    },
  ];

  const periods = ['전체', '당월', '전월', '당분기', '당년'];
  const statuses = ['전체', '출하 완료', '세금계산서 발행', '입금 완료'];

  const filteredSales = salesData.filter(sale => {
    const matchesSearch = sale.orderNo.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         sale.customer.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         sale.product.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = selectedStatus === '전체' || sale.status === selectedStatus;
    return matchesSearch && matchesStatus;
  });

  const totalSales = filteredSales.reduce((sum, sale) => sum + sale.totalAmount, 0);
  const totalVat = filteredSales.reduce((sum, sale) => sum + sale.vat, 0);
  const totalWithVat = filteredSales.reduce((sum, sale) => sum + sale.totalWithVat, 0);
  const unpaidAmount = filteredSales.filter(s => s.paymentStatus === '미수').reduce((sum, sale) => sum + sale.totalWithVat, 0);

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

  // 세금계산서 데이터 생성
  const generateTaxInvoiceData = (sale: SalesData) => {
    return {
      invoiceNo: sale.id,
      issueDate: sale.invoiceDate,
      supplier: {
        companyName: '(주)SAM 시스템',
        businessNo: '123-45-67890',
        representative: '홍길동',
        address: '서울특별시 강남구 테헤란로 123',
        businessType: '제조업',
        businessItem: '블라인드 제조',
        phone: '02-1234-5678',
        email: 'sam@company.com'
      },
      recipient: {
        companyName: sale.customer,
        businessNo: '234-56-78901',
        representative: '김대표',
        address: '서울특별시 서초구 서초대로 456',
        businessType: '제조업',
        businessItem: '전자제품',
        phone: '02-2345-6789',
        email: `${sale.customer.toLowerCase().replace(/\s/g, '')}@company.com`
      },
      items: [
        {
          date: sale.invoiceDate.slice(5),
          item: sale.product,
          spec: '표준',
          quantity: sale.quantity,
          unit: 'EA',
          unitPrice: sale.unitPrice,
          supplyAmount: sale.totalAmount,
          tax: sale.vat,
          note: sale.orderNo
        }
      ],
      totalSupplyAmount: sale.totalAmount,
      totalTax: sale.vat,
      totalAmount: sale.totalWithVat,
      note: `수주번호: ${sale.orderNo} / 담당자: ${sale.salesperson}`,
      type: 'sales' as const
    };
  };

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

  const columns: Column<SalesData>[] = [
    {
      key: 'invoiceDate',
      label: '계산서일자'
    },
    {
      key: 'orderNo',
      label: '수주번호'
    },
    {
      key: 'customer',
      label: '거래처'
    },
    {
      key: 'product',
      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={DollarSign}
        stats={[
          {
            label: "총 매출액",
            value: formatCurrency(totalSales),
            icon: DollarSign,
            iconColor: "text-blue-600",
            description: "공급가액"
          },
          {
            label: "부가세",
            value: formatCurrency(totalVat),
            icon: TrendingUp,
            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={filteredSales}
        keyField="id"
        columns={columns}
        renderMobileCard={(sale) => ({
          title: sale.customer,
          subtitle: `${sale.orderNo} | ${sale.invoiceDate}`,
          badge: {
            label: sale.status,
            variant: sale.status === '입금 완료' ? 'default' : 'secondary'
          },
          fields: [
            {
              label: "제품",
              value: sale.product
            },
            {
              label: "수량",
              value: `${sale.quantity.toLocaleString()}EA`
            },
            {
              label: "공급가액",
              value: formatCurrency(sale.totalAmount)
            },
            {
              label: "합계금액",
              value: formatCurrency(sale.totalWithVat),
              className: "font-semibold"
            },
            {
              label: "결제상태",
              value: sale.paymentStatus
            },
            {
              label: "담당자",
              value: sale.salesperson
            }
          ],
          actions: [
            {
              label: "세금계산서",
              icon: Eye,
              onClick: () => handleViewInvoice(sale)
            }
          ]
        })}
        emptyIcon={DollarSign}
        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>
    </>
  );
}