/**
 * 거래처 상세 페이지
 * IntegratedFormTemplateV3 템플릿 적용
 */

import { useState } from "react";
import { Building, FileText, DollarSign, History, Phone, MapPin, User, Mail, Calendar, Package, TrendingUp, AlertCircle, ArrowLeft, Edit, Trash2, Copy } from "lucide-react";
import {
  IntegratedFormTemplateV3,
  type IntegratedFormTemplateV3Config,
} from "./templates/IntegratedFormTemplateV3";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { toast } from "sonner@2.0.3";

// 거래처 인터페이스
interface Customer {
  id: string;
  code: string;
  name: string;
  type: "고객" | "공급업체" | "양방향";
  contact: string;
  phone: string;
  email?: string;
  fax?: string;
  address: string;
  detailedAddress?: string;
  businessNumber?: string;
  representative?: string;
  status: string;
  registeredDate?: string;
  credit?: string;
  paymentTerms?: string;
  notes?: string;
}

// 거래 내역 인터페이스
interface TransactionHistory {
  id: string;
  date: string;
  type: "수주" | "발주" | "견적" | "출하";
  documentNo: string;
  amount: number;
  status: string;
  description: string;
}

export function CustomerDetailPage() {
  // 예시 거래처 데이터
  const [customerData] = useState<Customer>({
    id: "C001",
    code: "CUST-001",
    name: "삼성전자",
    type: "고객",
    contact: "김구매",
    phone: "02-1234-5678",
    email: "kim.buyer@samsung.com",
    fax: "02-1234-5679",
    address: "서울시 강남구 테헤란로 123",
    detailedAddress: "삼성빌딩 5층",
    businessNumber: "123-45-67890",
    representative: "이재용",
    status: "활성",
    registeredDate: "2020-03-15",
    credit: "A+",
    paymentTerms: "월말 결제 (익월 15일)",
    notes: "주요 고객사, VIP 관리 필요"
  });

  // 거래 내역 데이터
  const transactionHistory: TransactionHistory[] = [
    {
      id: "1",
      date: "2025-01-20",
      type: "수주",
      documentNo: "SO-2025-001",
      amount: 125000000,
      status: "진행중",
      description: "방화문 KFD-001 200EA"
    },
    {
      id: "2",
      date: "2025-01-15",
      type: "견적",
      documentNo: "QT-2025-015",
      amount: 85000000,
      status: "확정",
      description: "자동도어 시스템 50SET"
    },
    {
      id: "3",
      date: "2025-01-10",
      type: "출하",
      documentNo: "SH-2025-008",
      amount: 95000000,
      status: "완료",
      description: "방화문 KFD-002 150EA"
    },
    {
      id: "4",
      date: "2024-12-28",
      type: "수주",
      documentNo: "SO-2024-245",
      amount: 180000000,
      status: "완료",
      description: "셔터도어 KQTS01 300EA"
    },
    {
      id: "5",
      date: "2024-12-15",
      type: "견적",
      documentNo: "QT-2024-198",
      amount: 120000000,
      status: "거절",
      description: "산업용 도어 100EA"
    }
  ];

  // 상품별 거래 통계
  const productStats = [
    {
      id: "1",
      itemCode: "KFD-001",
      itemName: "방화문 KFD-001",
      specification: "1500x2000",
      quantity: 450,
      unit: "EA",
      totalAmount: "4.5억원",
      status: "베스트셀러"
    },
    {
      id: "2",
      itemCode: "KQTS01",
      itemName: "셔터도어 KQTS01",
      specification: "2438x2438",
      quantity: 320,
      unit: "EA",
      totalAmount: "3.2억원",
      status: ""
    },
    {
      id: "3",
      itemCode: "KFD-002",
      itemName: "방화문 KFD-002",
      specification: "1200x2000",
      quantity: 280,
      unit: "EA",
      totalAmount: "2.1억원",
      status: ""
    }
  ];

  // 거래처 유형별 색상
  const getTypeColor = (type: string) => {
    switch (type) {
      case "고객":
        return "bg-blue-50 text-blue-700";
      case "공급업체":
        return "bg-green-50 text-green-700";
      case "양방향":
        return "bg-purple-50 text-purple-700";
      default:
        return "bg-gray-50 text-gray-700";
    }
  };

  // 거래 유형별 색상
  const getTransactionTypeColor = (type: string) => {
    switch (type) {
      case "수주":
        return "bg-green-50 text-green-700";
      case "발주":
        return "bg-blue-50 text-blue-700";
      case "견적":
        return "bg-yellow-50 text-yellow-700";
      case "출하":
        return "bg-purple-50 text-purple-700";
      default:
        return "bg-gray-50 text-gray-700";
    }
  };

  // 상태별 색상
  const getStatusColor = (status: string) => {
    switch (status) {
      case "진행중":
        return "bg-blue-50 text-blue-700";
      case "확정":
      case "완료":
        return "bg-green-50 text-green-700";
      case "거절":
      case "취소":
        return "bg-red-50 text-red-700";
      default:
        return "bg-gray-50 text-gray-700";
    }
  };

  // 금액 포맷
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ko-KR', {
      style: 'currency',
      currency: 'KRW'
    }).format(amount);
  };

  // 액션 버튼
  const actions = (
    <div className="flex gap-2">
      <Button variant="outline" size="sm" onClick={() => toast.info("목록으로 돌아갑니다")}>
        <ArrowLeft className="h-4 w-4 mr-1" />
        목록
      </Button>
      <Button variant="outline" size="sm" onClick={() => toast.info("수정 페이지로 이동합니다")}>
        <Edit className="h-4 w-4 mr-1" />
        수정
      </Button>
      <Button variant="outline" size="sm" onClick={() => toast.info("거래처를 복사합니다")}>
        <Copy className="h-4 w-4 mr-1" />
        복사
      </Button>
      <Button variant="destructive" size="sm" onClick={() => toast.warning("거래처를 삭제하시겠습니까?")}>
        <Trash2 className="h-4 w-4 mr-1" />
        삭제
      </Button>
    </div>
  );

  // IntegratedFormTemplateV3 설정
  const templateConfig: IntegratedFormTemplateV3Config = {
    // 헤더
    header: {
      title: "거래처 상세 정보",
      description: "등록된 거래처 정보를 확인합니다",
      icon: Building,
      actions: actions,
      badge: (
        <Badge variant="outline" className={getTypeColor(customerData.type)}>
          {customerData.type}
        </Badge>
      ),
    },

    // 버전 관리
    versionControl: {
      currentRevision: 2,
      revisions: [
        { updatedAt: "2020-03-15", description: "최초 등록" },
        { updatedAt: "2024-06-10", description: "담당자 정보 변경" },
      ],
      selectedRevision: "current",
      onRevisionChange: (revision) => console.log("버전 변경:", revision),
      itemType: "거래처",
      versionHistory: [
        {
          id: "1",
          version: 1,
          changeDescription: "최초 등록",
          changedBy: "김관리",
          changedAt: "2020-03-15T09:00:00Z",
        },
        {
          id: "2",
          version: 2,
          changeDescription: "담당자 정보 및 결제 조건 변경",
          changedBy: "이영희",
          changedAt: "2024-06-10T14:30:00Z",
        },
      ],
    },

    // 섹션들
    sections: [
      // 기본 정보
      {
        id: "basic-info",
        title: "기본 정보",
        icon: Building,
        gridCols: {
          default: 1,
          md: 2,
          lg: 3,
        },
        fields: [
          {
            label: "거래처 코드",
            value: customerData.code,
            type: "code",
          },
          {
            label: "거래처명",
            value: customerData.name,
          },
          {
            label: "거래처 유형",
            value: (
              <Badge variant="outline" className={getTypeColor(customerData.type)}>
                {customerData.type}
              </Badge>
            ),
            type: "badge",
          },
          {
            label: "사업자등록번호",
            value: customerData.businessNumber,
          },
          {
            label: "대표자명",
            value: customerData.representative,
          },
          {
            label: "상태",
            value: (
              <Badge variant="outline" className="bg-green-50 text-green-700">
                {customerData.status}
              </Badge>
            ),
            type: "badge",
          },
          {
            label: "신용등급",
            value: (
              <Badge variant="outline" className="bg-blue-50 text-blue-700">
                {customerData.credit}
              </Badge>
            ),
            type: "badge",
          },
          {
            label: "등록일",
            value: customerData.registeredDate,
          },
          {
            label: "비고",
            value: customerData.notes,
            span: 3,
          },
        ],
      },

      // 주소 정보
      {
        id: "address-info",
        title: "주소 정보",
        icon: MapPin,
        gridCols: {
          default: 1,
          md: 2,
        },
        fields: [
          {
            label: "기본 주소",
            value: customerData.address,
          },
          {
            label: "상세 주소",
            value: customerData.detailedAddress,
          },
        ],
      },

      // 담당자 및 연락처
      {
        id: "contact-info",
        title: "담당자 및 연락처",
        icon: Phone,
        gridCols: {
          default: 1,
          md: 2,
        },
        fields: [
          {
            label: "담당자",
            value: (
              <div className="flex items-center gap-2">
                <User className="h-4 w-4 text-muted-foreground" />
                <span>{customerData.contact}</span>
              </div>
            ),
            type: "custom",
          },
          {
            label: "전화번호",
            value: (
              <div className="flex items-center gap-2">
                <Phone className="h-4 w-4 text-muted-foreground" />
                <span>{customerData.phone}</span>
              </div>
            ),
            type: "custom",
          },
          {
            label: "이메일",
            value: (
              <div className="flex items-center gap-2">
                <Mail className="h-4 w-4 text-muted-foreground" />
                <span>{customerData.email}</span>
              </div>
            ),
            type: "custom",
          },
          {
            label: "팩스",
            value: customerData.fax,
          },
        ],
      },

      // 거래 조건
      {
        id: "payment-terms",
        title: "거래 조건",
        icon: DollarSign,
        gridCols: {
          default: 1,
        },
        fields: [
          {
            label: "결제 조건",
            value: customerData.paymentTerms,
            span: 1,
          },
        ],
      },
    ],

    // 테이블 섹션들
    tableSections: [
      // 거래 내역
      {
        id: "transaction-history",
        title: "거래 내역",
        icon: History,
        headerBadge: <Badge variant="secondary">최근 {transactionHistory.length}건</Badge>,
        columns: [
          { key: "date", label: "거래일자", width: "120px" },
          { 
            key: "type", 
            label: "유형", 
            width: "100px",
            render: (value) => (
              <Badge variant="outline" className={getTransactionTypeColor(value)}>
                {value}
              </Badge>
            )
          },
          { key: "documentNo", label: "문서번호", width: "150px" },
          { key: "description", label: "내용" },
          { 
            key: "amount", 
            label: "금액", 
            width: "140px",
            render: (value) => (
              <span className="font-medium">{formatCurrency(value)}</span>
            )
          },
          { 
            key: "status", 
            label: "상태", 
            width: "100px",
            render: (value) => (
              <Badge variant="outline" className={getStatusColor(value)}>
                {value}
              </Badge>
            )
          },
        ],
        data: transactionHistory,
        responsive: true,
        emptyMessage: "거래 내역이 없습니다",
      },

      // 상품별 거래 현황
      {
        id: "product-stats",
        title: "상품별 거래 현황",
        icon: TrendingUp,
        headerBadge: <Badge variant="secondary">총 {productStats.length}개 품목</Badge>,
        columns: [
          { key: "itemCode", label: "품목코드", width: "120px" },
          { key: "itemName", label: "품목명" },
          { key: "specification", label: "규격", width: "120px" },
          { 
            key: "quantity", 
            label: "누적 수량", 
            width: "100px",
            render: (value, row) => `${value} ${row.unit}`
          },
          { 
            key: "totalAmount", 
            label: "누적 금액", 
            width: "120px",
            className: "font-medium"
          },
          { 
            key: "status", 
            label: "비고", 
            width: "120px",
            render: (value) => value ? (
              <Badge variant="outline" className="bg-purple-50 text-purple-700">
                {value}
              </Badge>
            ) : "-"
          },
        ],
        data: productStats,
        responsive: true,
        emptyMessage: "거래 현황이 없습니다",
      },
    ],

    // 이미지 갤러리
    imageGallery: {
      title: "첨부 파일 및 문서",
      icon: FileText,
      columns: {
        default: 1,
        md: 2,
        lg: 3,
      },
      images: [
        {
          id: "1",
          url: "https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=400",
          alt: "사업자등록증",
          caption: "사업자등록증"
        },
        {
          id: "2",
          url: "https://images.unsplash.com/photo-1497366216548-37526070297c?w=400",
          alt: "통장사본",
          caption: "통장사본"
        },
        {
          id: "3",
          url: "https://images.unsplash.com/photo-1450101499163-c8848c66ca85?w=400",
          alt: "계약서",
          caption: "기본 거래 계약서"
        }
      ],
    },

    maxWidth: "default",
  };

  return <IntegratedFormTemplateV3 config={templateConfig} />;
}

export default CustomerDetailPage;
