"use client";

/**
 * ERP 마스터 동기화 (자동화 관리 > 배치 관리 > ERP 동기화)
 *
 * 외부 ERP(Wehago/RPS) REST API를 호출해 사원·부서·창고·거래처·계정과목 정보를
 * 내부 DB(user_info / dept_info / warehouse_info / customer_mng / account_code_info)에
 * UPSERT 합니다. 백엔드 라우트는 /api/erp-sync/*.
 */
import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Building2,
  Users,
  Warehouse,
  Briefcase,
  BookOpen,
  PlayCircle,
  Loader2,
  CheckCircle2,
  AlertCircle,
} from "lucide-react";
import { toast } from "sonner";
import { ErpSyncAPI, type ErpSyncResult } from "@/lib/api/erpSync";

type ResourceKey = "departments" | "employees" | "warehouses" | "customers" | "account-codes";

const RESOURCE_DEFS: Array<{
  key: ResourceKey;
  label: string;
  table: string;
  icon: React.ComponentType<{ className?: string }>;
  description: string;
}> = [
  {
    key: "departments",
    label: "부서",
    table: "dept_info",
    icon: Building2,
    description: "Wehago api16S10 — 회사의 부서 마스터를 가져와 dept_info 에 적재합니다.",
  },
  {
    key: "employees",
    label: "사원",
    table: "user_info",
    icon: Users,
    description: "Wehago api16S05 — 사원 목록(이메일/연락처 포함)을 user_info 에 적재합니다.",
  },
  {
    key: "warehouses",
    label: "창고",
    table: "warehouse_info",
    icon: Warehouse,
    description: "Wehago api20A00S00801 — 창고/위치 마스터를 warehouse_info 에 적재합니다.",
  },
  {
    key: "customers",
    label: "거래처",
    table: "customer_mng",
    icon: Briefcase,
    description: "Wehago api16S11 — 거래처 마스터를 customer_mng 에 적재합니다.",
  },
  {
    key: "account-codes",
    label: "계정과목",
    table: "account_code_info",
    icon: BookOpen,
    description: "Wehago api11A02 — 계정과목을 account_code_info 에 적재합니다.",
  },
];

export default function ErpSyncPage() {
  const [coCd, setCoCd] = useState<string>("2000");
  const [companyCode, setCompanyCode] = useState<string>("COMPANY_16");
  const [busy, setBusy] = useState<ResourceKey | "all" | null>(null);
  const [results, setResults] = useState<Record<string, ErpSyncResult>>({});

  const handleSyncOne = async (key: ResourceKey) => {
    if (!coCd.trim()) {
      toast.error("회사코드(coCd) 를 입력해 주세요.");
      return;
    }
    setBusy(key);
    try {
      const result = await ErpSyncAPI.syncOne(key, { coCd: coCd.trim(), companyCode: companyCode.trim() });
      setResults((prev) => ({ ...prev, [key]: result }));
      if (result.errors.length === 0) {
        toast.success(`${labelOf(key)} 동기화 완료 — 신규 ${result.inserted}건 / 갱신 ${result.updated}건`);
      } else {
        toast.error(`${labelOf(key)} 동기화 실패 — ${result.errors[0]}`);
      }
    } catch (e: any) {
      toast.error(e?.message || `${labelOf(key)} 동기화 중 오류`);
    } finally {
      setBusy(null);
    }
  };

  const handleSyncAll = async () => {
    if (!coCd.trim()) {
      toast.error("회사코드(coCd) 를 입력해 주세요.");
      return;
    }
    setBusy("all");
    try {
      const { totals, results: list } = await ErpSyncAPI.syncAll({
        coCd: coCd.trim(),
        companyCode: companyCode.trim(),
      });
      const next: Record<string, ErpSyncResult> = {};
      for (const r of list) {
        const k = r.resource === "accountCodes" ? "account-codes" : r.resource;
        next[k] = r;
      }
      setResults((prev) => ({ ...prev, ...next }));
      if (totals && totals.errorsCount === 0) {
        toast.success(`전체 동기화 완료 — 신규 ${totals.inserted}건 / 갱신 ${totals.updated}건`);
      } else {
        toast.error(`전체 동기화 — 오류 ${totals?.errorsCount ?? 0}건 발생`);
      }
    } catch (e: any) {
      toast.error(e?.message || "전체 동기화 중 오류");
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="h-full overflow-y-auto bg-background">
      <div className="w-full max-w-5xl space-y-6 px-4 py-6 sm:px-6">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h1 className="text-lg font-bold tracking-tight">ERP 마스터 동기화</h1>
            <p className="text-xs text-muted-foreground">
              외부 ERP에서 사원·부서·창고·거래처·계정과목을 가져와 내부 DB에 적재해요.
            </p>
          </div>
          <Button onClick={handleSyncAll} disabled={busy !== null} className="h-9 gap-2">
            {busy === "all" ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <PlayCircle className="h-4 w-4" />
            )}
            전체 동기화
          </Button>
        </div>

        {/* 입력 영역 */}
        <div className="rounded-lg border bg-card p-4">
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="space-y-1.5">
              <Label htmlFor="coCd" className="text-xs">
                회사코드(coCd) — ERP 4자리 회사코드
              </Label>
              <Input
                id="coCd"
                value={coCd}
                onChange={(e) => setCoCd(e.target.value)}
                placeholder="예: 2000"
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="companyCode" className="text-xs">
                내부 회사코드(companyCode) — 적재 대상
              </Label>
              <Input
                id="companyCode"
                value={companyCode}
                onChange={(e) => setCompanyCode(e.target.value)}
                placeholder="예: COMPANY_16"
                className="h-9 text-sm"
              />
            </div>
          </div>
        </div>

        {/* 리소스 카드 */}
        <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
          {RESOURCE_DEFS.map(({ key, label, table, icon: Icon, description }) => {
            const r = results[key];
            const running = busy === key;
            const success = r && r.errors.length === 0;
            return (
              <div key={key} className="flex flex-col gap-3 rounded-lg border bg-card p-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex items-center gap-2">
                    <div className="flex h-8 w-8 items-center justify-center rounded-md bg-primary/10 text-primary">
                      <Icon className="h-4 w-4" />
                    </div>
                    <div>
                      <div className="text-sm font-semibold">{label}</div>
                      <div className="text-[11px] text-muted-foreground">{table}</div>
                    </div>
                  </div>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleSyncOne(key)}
                    disabled={busy !== null}
                    className="h-8 gap-1 text-xs"
                  >
                    {running ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlayCircle className="h-3.5 w-3.5" />}
                    실행
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground">{description}</p>

                {r && (
                  <div className="space-y-2 rounded-md border bg-muted/20 p-2 text-xs">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        {success ? (
                          <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
                        ) : (
                          <AlertCircle className="h-3.5 w-3.5 text-destructive" />
                        )}
                        <span className="font-semibold">
                          {success ? "성공" : "실패"}
                        </span>
                      </div>
                      <span className="text-[10px] text-muted-foreground">
                        {(r.durationMs / 1000).toFixed(2)}초
                      </span>
                    </div>
                    <div className="flex flex-wrap gap-1.5">
                      <Badge variant="secondary" className="text-[10px]">
                        조회 {r.fetched}
                      </Badge>
                      <Badge className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/20 text-[10px]">
                        신규 {r.inserted}
                      </Badge>
                      <Badge className="bg-blue-500/15 text-blue-700 hover:bg-blue-500/20 text-[10px]">
                        갱신 {r.updated}
                      </Badge>
                      {r.skipped > 0 && (
                        <Badge variant="outline" className="text-[10px]">
                          건너뜀 {r.skipped}
                        </Badge>
                      )}
                    </div>
                    {r.errors.length > 0 && (
                      <div className="rounded bg-destructive/10 p-1.5 text-[11px] text-destructive">
                        {r.errors[0]}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        <div className="rounded-lg border-l-2 border-blue-500 bg-blue-500/5 p-3 text-xs text-muted-foreground">
          <div className="font-semibold text-foreground">ERP 인증/엔드포인트</div>
          <ul className="mt-1.5 list-inside list-disc space-y-1">
            <li>baseUrl: <code className="rounded bg-muted px-1">ERP_BASE_URL</code> (기본 https://erp.rps-korea.com)</li>
            <li>인증: callerName + Bearer 토큰 + transaction-id + timestamp + groupSeq + wehago-sign(HMAC-SHA256)</li>
            <li>참고 원본: <code className="rounded bg-muted px-1">/Users/chpark/wace_plm/src/com/pms/api</code> (Java)</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

function labelOf(k: ResourceKey): string {
  return RESOURCE_DEFS.find((d) => d.key === k)?.label ?? k;
}
