/**
 * 거래처 관리 - 디자인 시스템 적용 예제
 * 
 * BasicDesktopListTemplate을 적용한 거래처 관리 페이지입니다.
 * - 품목관리와 동일한 스타일
 * - 데스크톱: BasicDesktopListTemplate 템플릿
 * - 모바일: MobileCard 리스트
 */

import { useState } from "react";
import { Building2, Plus, Edit, Eye, Trash2 } from "lucide-react";
import { BasicDesktopListTemplate } from "./templates/BasicDesktopListTemplate";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { MobileCard } from "./organisms/MobileCard";
import { Column } from "./organisms/DataTable";
import { toast } from "sonner@2.0.3";

// 거래처 데이터 타입
interface ClientData {
  id: string;
  code: string;
  businessNumber: string;
  name: string;
  type: "매입" | "매출" | "매입매출";
  representative: string;
  address: string;
  businessType: string;
  businessCategory: string;
  phone: string;
  mobile: string;
  fax: string;
  email: string;
  managerName: string;
  managerTel: string;
  memo: string;
  accountId: string;
  accountPassword: string;
  purchasePaymentDay: string;
  salesPaymentDay: string;
  taxAgreement: boolean;
  taxAmount: string;
  taxStartDate: string;
  taxEndDate: string;
  status: "활성" | "비활성";
  manager: string;
  badDebt: boolean;
  badDebtAmount: string;
  badDebtReceiveDate: string;
  badDebtEndDate: string;
  badDebtProgress: string;
}

// 샘플 거래처 데이터
const SAMPLE_CLIENTS: ClientData[] = [
  {
    id: "1",
    code: "2083",
    businessNumber: "1378627566",
    name: "오정건설주식회사",
    type: "매입",
    representative: "이정민",
    address: "경기도 김포시 통진읍 김포대로2462번길 8 1층",
    businessType: "수집운반업",
    businessCategory: "폐기물수집운반",
    phone: "010-8755-4335",
    mobile: "",
    fax: "",
    email: "a9874577@naver.com",
    managerName: "",
    managerTel: "",
    memo: "",
    accountId: "",
    accountPassword: "",
    purchasePaymentDay: "말일",
    salesPaymentDay: "말일",
    taxAgreement: false,
    taxAmount: "",
    taxStartDate: "",
    taxEndDate: "",
    status: "활성",
    manager: "김담당",
    badDebt: false,
    badDebtAmount: "",
    badDebtReceiveDate: "",
    badDebtEndDate: "",
    badDebtProgress: "",
  },
  {
    id: "2",
    code: "2084",
    businessNumber: "0104484748",
    name: "가올산업",
    type: "매출",
    representative: "김철수",
    address: "서울시 강남구 테헤란로 123",
    businessType: "도매",
    businessCategory: "건축자재",
    phone: "010-5555-1234",
    mobile: "010-1234-5678",
    fax: "02-555-5678",
    email: "info@gaol.com",
    managerName: "박영희",
    managerTel: "010-9876-5432",
    memo: "주요 거래처",
    accountId: "gaol123",
    accountPassword: "",
    purchasePaymentDay: "10일",
    salesPaymentDay: "15일",
    taxAgreement: true,
    taxAmount: "1000000",
    taxStartDate: "2024-01-01",
    taxEndDate: "2024-12-31",
    status: "활성",
    manager: "이담당",
    badDebt: true,
    badDebtAmount: "5000000",
    badDebtReceiveDate: "2024-01-15",
    badDebtEndDate: "2024-12-31",
    badDebtProgress: "1차 독촉장 발송 완료",
  },
  {
    id: "3",
    code: "2085",
    businessNumber: "1234567890",
    name: "조일알미늄 유리공사",
    type: "매입매출",
    representative: "조영수",
    address: "인천시 부평구 산업로 456",
    businessType: "제조",
    businessCategory: "알미늄",
    phone: "032-123-4567",
    mobile: "010-2222-3333",
    fax: "032-123-4568",
    email: "joil@example.com",
    managerName: "최현준",
    managerTel: "010-3333-4444",
    memo: "",
    accountId: "joil_alu",
    accountPassword: "",
    purchasePaymentDay: "말일",
    salesPaymentDay: "20일",
    taxAgreement: false,
    taxAmount: "",
    taxStartDate: "",
    taxEndDate: "",
    status: "활성",
    manager: "박담당",
    badDebt: false,
    badDebtAmount: "",
    badDebtReceiveDate: "",
    badDebtEndDate: "",
    badDebtProgress: "",
  },
];

export function ClientManagement_DesignSystemExample({ filterByType }: { filterByType?: 'all' | 'purchase' | 'sales' }) {
  const [clients] = useState<ClientData[]>(SAMPLE_CLIENTS);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterType, setFilterType] = useState<string>(filterByType || "all");
  const [filterStatus, setFilterStatus] = useState<string>("all");

  // 필터링된 거래처
  const filteredClients = clients.filter((client) => {
    const matchesSearch =
      searchQuery === "" ||
      client.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      client.businessNumber.includes(searchQuery) ||
      client.representative.toLowerCase().includes(searchQuery.toLowerCase());

    const matchesType = filterType === "all" || client.type === filterType;
    const matchesStatus = filterStatus === "all" || client.status === filterStatus;

    return matchesSearch && matchesType && matchesStatus;
  });

  // 통계 데이터
  const stats = [
    {
      label: "전체 거래처",
      value: clients.length.toString(),
      icon: Building2,
      color: "text-blue-600" as const,
    },
    {
      label: "매입처",
      value: clients.filter((c) => c.type === "매입" || c.type === "매입매출").length.toString(),
      icon: Building2,
      color: "text-orange-600" as const,
    },
    {
      label: "매출처",
      value: clients.filter((c) => c.type === "매출" || c.type === "매입매출").length.toString(),
      icon: Building2,
      color: "text-green-600" as const,
    },
    {
      label: "악성채권 발생",
      value: clients.filter((c) => c.badDebt).length.toString(),
      icon: Building2,
      color: "text-red-600" as const,
    },
  ];

  // 테이블 컬럼 정의
  const columns: Column<ClientData>[] = [
    {
      key: "code",
      label: "코드",
      width: "w-24",
      render: (client) => <span className="font-medium">{client.code}</span>,
    },
    {
      key: "type",
      label: "구분",
      width: "w-28",
      render: (client) => (
        <Badge
          className={
            client.type === "매입"
              ? "bg-orange-100 text-orange-800 border-orange-300"
              : client.type === "매출"
              ? "bg-green-100 text-green-800 border-green-300"
              : "bg-blue-100 text-blue-800 border-blue-300"
          }
        >
          {client.type}
        </Badge>
      ),
    },
    {
      key: "name",
      label: "거래처명",
      width: "w-48",
      render: (client) => <span>{client.name}</span>,
    },
    {
      key: "representative",
      label: "대표자",
      width: "w-28",
      render: (client) => <span>{client.representative}</span>,
    },
    {
      key: "managerName",
      label: "담당자",
      width: "w-28",
      render: (client) => <span>{client.managerName || "-"}</span>,
    },
    {
      key: "phone",
      label: "전화번호",
      width: "w-36",
      render: (client) => <span>{client.phone}</span>,
    },
    {
      key: "purchasePaymentDay",
      label: "매입 결제일",
      width: "w-28",
      render: (client) => <span>{client.purchasePaymentDay}</span>,
    },
    {
      key: "salesPaymentDay",
      label: "매출 결제일",
      width: "w-28",
      render: (client) => <span>{client.salesPaymentDay}</span>,
    },
    {
      key: "badDebt",
      label: "악성채권",
      width: "w-24",
      align: "center",
      render: (client) =>
        client.badDebt ? (
          <Badge className="bg-red-100 text-red-800 border-red-300">발생</Badge>
        ) : (
          <Badge className="bg-gray-100 text-gray-800 border-gray-300">정상</Badge>
        ),
    },
    {
      key: "badDebtAmount",
      label: "악성채권 금액",
      width: "w-32",
      align: "right",
      render: (client) => (
        <span>{client.badDebtAmount ? `₩${Number(client.badDebtAmount).toLocaleString()}` : "-"}</span>
      ),
    },
  ];

  // 액션 정의
  const actions = [
    {
      label: "상세",
      icon: Eye,
      variant: "ghost" as const,
      onClick: (client: ClientData) => {
        toast.info(`${client.name} 상세보기`);
      },
    },
    {
      label: "수정",
      icon: Edit,
      variant: "ghost" as const,
      onClick: (client: ClientData) => {
        toast.info(`${client.name} 수정`);
      },
    },
    {
      label: "삭제",
      icon: Trash2,
      variant: "ghost" as const,
      onClick: (client: ClientData) => {
        if (confirm(`${client.name}을(를) 삭제하시겠습니까?`)) {
          toast.success("삭제되었습니다");
        }
      },
    },
  ];

  // 필터 옵션
  const filters = [
    {
      label: "구분",
      value: filterType,
      onChange: setFilterType,
      options: [
        { label: "전체", value: "all" },
        { label: "매입", value: "매입" },
        { label: "매출", value: "매출" },
        { label: "매입매출", value: "매입매출" },
      ],
    },
    {
      label: "상태",
      value: filterStatus,
      onChange: setFilterStatus,
      options: [
        { label: "전체", value: "all" },
        { label: "활성", value: "활성" },
        { label: "비활성", value: "비활성" },
      ],
    },
  ];

  // 데스크톱 뷰
  const DesktopView = (
    <BasicDesktopListTemplate
      title="거래처 관리"
      description="매출처/매입처 거래처 정보를 관리합니다"
      icon={Building2}
      stats={stats}
      columns={columns}
      data={filteredClients}
      actions={actions}
      onAdd={() => toast.info("거래처 등록")}
      addText="거래처 등록"
      searchValue={searchQuery}
      onSearchChange={setSearchQuery}
      searchPlaceholder="거래처명, 사업자번호, 대표자로 검색"
      filters={filters}
      onRowClick={(client) => toast.info(`${client.name} 클릭`)}
      emptyTitle="등록된 거래처가 없습니다"
      emptyDescription="새로운 거래처를 등록해주세요"
    />
  );

  // 모바일 뷰
  const MobileView = (
    <div className="lg:hidden space-y-4">
      {filteredClients.map((client) => (
        <MobileCard
          key={client.id}
          title={client.name}
          subtitle={`${client.code} | ${client.representative}`}
          badge={{
            label: client.type,
            variant:
              client.type === "매입" ? "outline" : client.type === "매출" ? "default" : "secondary",
          }}
          fields={[
            { label: "담당자", value: client.managerName || "-" },
            { label: "전화", value: client.phone },
            { label: "매입 결제일", value: client.purchasePaymentDay },
            { label: "매출 결제일", value: client.salesPaymentDay },
            {
              label: "악성채권",
              value: client.badDebt ? "발생" : "정상",
              badge: true,
              badgeVariant: client.badDebt ? "destructive" : "secondary",
            },
            {
              label: "악성채권 금액",
              value: client.badDebtAmount ? `₩${Number(client.badDebtAmount).toLocaleString()}` : "-",
            },
          ]}
          actions={[
            {
              label: "상세",
              icon: Eye,
              variant: "outline",
              onClick: () => toast.info(`${client.name} 상세보기`),
            },
            {
              label: "수정",
              icon: Edit,
              variant: "outline",
              onClick: () => toast.info(`${client.name} 수정`),
            },
            {
              label: "삭제",
              icon: Trash2,
              variant: "outline",
              onClick: () => {
                if (confirm(`${client.name}을(를) 삭제하시겠습니까?`)) {
                  toast.success("삭제되었습니다");
                }
              },
            },
          ]}
        />
      ))}
    </div>
  );

  return (
    <>
      {/* 데스크톱 화면 */}
      <div className="hidden lg:block">{DesktopView}</div>

      {/* 모바일 화면 */}
      <div className="lg:hidden">{MobileView}</div>
    </>
  );
}
