/**
 * CRUDPageTemplate 사용 예시
 * 
 * 거래처 관리를 CRUDPageTemplate으로 구현한 예시입니다.
 * 이 패턴을 다른 페이지(품목관리, 현장관리, 사용자관리 등)에도 동일하게 적용할 수 있습니다.
 */

import { useState } from "react";
import { CRUDPageTemplate } from "../templates/CRUDPageTemplate";
import { Column } from "../organisms/DataTable";
import { Building2, Phone, Mail, User, MapPin } from "lucide-react";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Textarea } from "../ui/textarea";
import { Badge } from "../ui/badge";
import { useData, Client } from "../contexts/DataContext";

export function ClientManagementExample() {
  const { clients, addClient, updateClient, deleteClient } = useData();
  
  // 컬럼 정의
  const columns: Column<Client>[] = [
    {
      key: "code",
      label: "거래처 코드",
      render: (client) => <span className="font-mono">{client.code}</span>,
    },
    {
      key: "name",
      label: "거래처명",
      render: (client) => (
        <div className="flex items-center gap-2">
          <Building2 className="w-4 h-4 text-blue-600" />
          <span className="font-medium">{client.name}</span>
        </div>
      ),
    },
    {
      key: "type",
      label: "구분",
      render: (client) => (
        <Badge variant={client.type === "매출" ? "default" : "secondary"}>
          {client.type}
        </Badge>
      ),
    },
    {
      key: "businessNumber",
      label: "사업자번호",
    },
    {
      key: "representative",
      label: "대표자",
      render: (client) => (
        <div className="flex items-center gap-1">
          <User className="w-3 h-3 text-muted-foreground" />
          {client.representative}
        </div>
      ),
    },
    {
      key: "phone",
      label: "연락처",
      render: (client) => (
        <div className="flex items-center gap-1">
          <Phone className="w-3 h-3 text-muted-foreground" />
          {client.phone}
        </div>
      ),
    },
    {
      key: "status",
      label: "상태",
      render: (client) => (
        <Badge variant={client.status === "활성" ? "default" : "secondary"}>
          {client.status}
        </Badge>
      ),
    },
  ];
  
  // 통계
  const stats = [
    {
      label: "전체 거래처",
      value: clients.length,
      icon: Building2,
      iconColor: "text-blue-600",
    },
    {
      label: "매출 거래처",
      value: clients.filter(c => c.type === "매출" || c.type === "매입매출").length,
      icon: Building2,
      iconColor: "text-green-600",
    },
    {
      label: "매입 거래처",
      value: clients.filter(c => c.type === "매입" || c.type === "매입매출").length,
      icon: Building2,
      iconColor: "text-orange-600",
    },
    {
      label: "활성 거래처",
      value: clients.filter(c => c.status === "활성").length,
      icon: Building2,
      iconColor: "text-purple-600",
    },
  ];
  
  // 폼 렌더링
  const renderForm = (
    formData: Partial<Client> | null,
    onChange: (field: keyof Client, value: any) => void,
    errors?: Record<string, string>
  ) => {
    if (!formData) return null;
    
    return (
      <div className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* 거래처 코드 */}
          <div>
            <Label>거래처 코드 *</Label>
            <Input
              value={formData.code || ""}
              onChange={(e) => onChange("code", e.target.value)}
              placeholder="C0001"
            />
            {errors?.code && <p className="text-sm text-red-600 mt-1">{errors.code}</p>}
          </div>
          
          {/* 거래처명 */}
          <div>
            <Label>거래처명 *</Label>
            <Input
              value={formData.name || ""}
              onChange={(e) => onChange("name", e.target.value)}
              placeholder="거래처명을 입력하세요"
            />
            {errors?.name && <p className="text-sm text-red-600 mt-1">{errors.name}</p>}
          </div>
          
          {/* 구분 */}
          <div>
            <Label>거래 구분 *</Label>
            <Select
              value={formData.type || ""}
              onValueChange={(value) => onChange("type", value as Client["type"])}
            >
              <SelectTrigger>
                <SelectValue placeholder="구분 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="매입">매입</SelectItem>
                <SelectItem value="매출">매출</SelectItem>
                <SelectItem value="매입매출">매입매출</SelectItem>
              </SelectContent>
            </Select>
            {errors?.type && <p className="text-sm text-red-600 mt-1">{errors.type}</p>}
          </div>
          
          {/* 사업자번호 */}
          <div>
            <Label>사업자번호</Label>
            <Input
              value={formData.businessNumber || ""}
              onChange={(e) => onChange("businessNumber", e.target.value)}
              placeholder="000-00-00000"
            />
          </div>
          
          {/* 대표자 */}
          <div>
            <Label>대표자</Label>
            <Input
              value={formData.representative || ""}
              onChange={(e) => onChange("representative", e.target.value)}
              placeholder="대표자명"
            />
          </div>
          
          {/* 전화번호 */}
          <div>
            <Label>전화번호</Label>
            <Input
              value={formData.phone || ""}
              onChange={(e) => onChange("phone", e.target.value)}
              placeholder="02-1234-5678"
            />
          </div>
          
          {/* 휴대전화 */}
          <div>
            <Label>휴대전화</Label>
            <Input
              value={formData.mobile || ""}
              onChange={(e) => onChange("mobile", e.target.value)}
              placeholder="010-1234-5678"
            />
          </div>
          
          {/* 팩스 */}
          <div>
            <Label>팩스</Label>
            <Input
              value={formData.fax || ""}
              onChange={(e) => onChange("fax", e.target.value)}
              placeholder="02-1234-5679"
            />
          </div>
          
          {/* 이메일 */}
          <div>
            <Label>이메일</Label>
            <Input
              type="email"
              value={formData.email || ""}
              onChange={(e) => onChange("email", e.target.value)}
              placeholder="email@example.com"
            />
          </div>
          
          {/* 업태 */}
          <div>
            <Label>업태</Label>
            <Input
              value={formData.businessType || ""}
              onChange={(e) => onChange("businessType", e.target.value)}
              placeholder="제조업"
            />
          </div>
          
          {/* 종목 */}
          <div>
            <Label>종목</Label>
            <Input
              value={formData.businessCategory || ""}
              onChange={(e) => onChange("businessCategory", e.target.value)}
              placeholder="철강가공"
            />
          </div>
          
          {/* 담당자명 */}
          <div>
            <Label>담당자명</Label>
            <Input
              value={formData.managerName || ""}
              onChange={(e) => onChange("managerName", e.target.value)}
              placeholder="담당자명"
            />
          </div>
          
          {/* 담당자 연락처 */}
          <div>
            <Label>담당자 연락처</Label>
            <Input
              value={formData.managerTel || ""}
              onChange={(e) => onChange("managerTel", e.target.value)}
              placeholder="010-1234-5678"
            />
          </div>
          
          {/* 상태 */}
          <div>
            <Label>상태</Label>
            <Select
              value={formData.status || "활성"}
              onValueChange={(value) => onChange("status", value as Client["status"])}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="활성">활성</SelectItem>
                <SelectItem value="비활성">비활성</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        
        {/* 주소 */}
        <div>
          <Label>주소</Label>
          <Input
            value={formData.address || ""}
            onChange={(e) => onChange("address", e.target.value)}
            placeholder="주소를 입력하세요"
          />
        </div>
        
        {/* 메모 */}
        <div>
          <Label>메모</Label>
          <Textarea
            value={formData.memo || ""}
            onChange={(e) => onChange("memo", e.target.value)}
            placeholder="특이사항을 입력하세요"
            rows={4}
          />
        </div>
      </div>
    );
  };
  
  // 상세보기 렌더링
  const renderDetail = (client: Client) => {
    return (
      <div className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <div className="text-sm text-muted-foreground mb-1">거래처 코드</div>
            <div className="font-mono">{client.code}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">거래처명</div>
            <div className="font-semibold">{client.name}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">구분</div>
            <Badge variant={client.type === "매출" ? "default" : "secondary"}>
              {client.type}
            </Badge>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">사업자번호</div>
            <div>{client.businessNumber || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">대표자</div>
            <div>{client.representative || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">전화번호</div>
            <div className="flex items-center gap-2">
              <Phone className="w-4 h-4 text-muted-foreground" />
              {client.phone || "-"}
            </div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">휴대전화</div>
            <div>{client.mobile || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">이메일</div>
            <div className="flex items-center gap-2">
              <Mail className="w-4 h-4 text-muted-foreground" />
              {client.email || "-"}
            </div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">업태</div>
            <div>{client.businessType || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">종목</div>
            <div>{client.businessCategory || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">담당자</div>
            <div>{client.managerName || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">담당자 연락처</div>
            <div>{client.managerTel || "-"}</div>
          </div>
          
          <div>
            <div className="text-sm text-muted-foreground mb-1">상태</div>
            <Badge variant={client.status === "활성" ? "default" : "secondary"}>
              {client.status}
            </Badge>
          </div>
        </div>
        
        <div>
          <div className="text-sm text-muted-foreground mb-1">주소</div>
          <div className="flex items-start gap-2">
            <MapPin className="w-4 h-4 text-muted-foreground mt-0.5" />
            {client.address || "-"}
          </div>
        </div>
        
        {client.memo && (
          <div>
            <div className="text-sm text-muted-foreground mb-1">메모</div>
            <div className="bg-muted/50 p-3 rounded-lg">{client.memo}</div>
          </div>
        )}
      </div>
    );
  };
  
  // 모바일 카드 렌더링
  const renderMobileCard = (client: Client) => ({
    title: client.name,
    subtitle: client.code,
    icon: <Building2 className="w-4 h-4 text-blue-600" />,
    badge: {
      label: client.type,
      variant: (client.type === "매출" ? "default" : "secondary") as any,
    },
    fields: [
      { label: "대표자", value: client.representative || "-" },
      { label: "연락처", value: client.phone || "-" },
      { label: "상태", value: client.status },
    ],
  });
  
  // 폼 검증
  const validateForm = (data: Partial<Client>) => {
    const errors: Record<string, string> = {};
    
    if (!data.code?.trim()) {
      errors.code = "거래처 코드는 필수입니다";
    }
    
    if (!data.name?.trim()) {
      errors.name = "거래처명은 필수입니다";
    }
    
    if (!data.type) {
      errors.type = "거래 구분을 선택해주세요";
    }
    
    return Object.keys(errors).length > 0 ? errors : null;
  };
  
  // 초기 폼 데이터
  const getDefaultFormData = (): Partial<Client> => ({
    code: "",
    name: "",
    type: "매출",
    businessNumber: "",
    representative: "",
    address: "",
    businessType: "",
    businessCategory: "",
    phone: "",
    mobile: "",
    fax: "",
    email: "",
    managerName: "",
    managerTel: "",
    memo: "",
    status: "활성",
  });
  
  // 액션 핸들러
  const handleCreate = async (data: Partial<Client>) => {
    const newClient: Client = {
      ...data as Client,
      id: `CLI-${Date.now()}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    addClient(newClient);
  };
  
  const handleUpdate = async (id: string, data: Partial<Client>) => {
    updateClient(id, {
      ...data,
      updatedAt: new Date().toISOString(),
    });
  };
  
  const handleDelete = async (id: string) => {
    deleteClient(id);
  };
  
  return (
    <CRUDPageTemplate
      title="거래처 관리"
      description="매입/매출 거래처 정보를 등록하고 관리합니다"
      icon={Building2}
      data={clients}
      columns={columns}
      stats={stats}
      searchPlaceholder="거래처 코드, 거래처명, 대표자로 검색..."
      searchFields={["code", "name", "representative", "phone"]}
      renderForm={renderForm}
      renderDetail={renderDetail}
      renderMobileCard={renderMobileCard}
      validateForm={validateForm}
      getDefaultFormData={getDefaultFormData}
      onCreate={handleCreate}
      onUpdate={handleUpdate}
      onDelete={handleDelete}
      emptyIcon={Building2}
      emptyTitle="등록된 거래처가 없습니다"
      emptyDescription="첫 거래처를 등록해보세요"
    />
  );
}
