"use client";

import { useEffect, useState, useRef } from "react";
import Link from "next/link";
import { Download, Image as ImageIcon, X, Eye, Trash2 } from "lucide-react";
import Swal from "sweetalert2";
import { downloadXlsx } from "@/lib/xlsx-export";
import { captureAndShare as captureAndShareLib } from "@/lib/capture-share";
import { useAuthStore } from "@/store/auth-store";

interface Order {
  OBJID: string;
  ORDER_NO: string;
  ORDER_DATE: string;
  STATUS: string;
  TOTAL_AMOUNT: number;
  TOTAL_TAXFREE: number;
  TOTAL_TAXABLE: number;
  TOTAL_SUPPLY?: number;
  TOTAL_VAT?: number;
  COMPANY_NAME?: string;
}
interface DetailLine {
  OBJID: string; SEQ: number; ITEM_NAME: string; UNIT?: string;
  UNIT_PRICE: number; QTY: number; IS_TAX_FREE: string;
  SUPPLY_AMOUNT: number; VAT_AMOUNT: number; TOTAL_AMOUNT: number;
  KIND: "ITEM" | "DELIVERY" | "CHARTER"; EXTRA_LABEL?: string; REMARK?: string;
}
interface Supplier {
  NAME: string; CEO: string; BIZ_NO: string;
  BANK_ACCOUNT: string; PHONE: string; EMAIL: string; ADDRESS: string;
}

const fmt = (n: number | string | undefined) => Number(n || 0).toLocaleString("ko-KR");
const STATUS_LABEL: Record<string, string> = {
  REQUESTED: "출고요청", APPROVED: "출고완료",
  PAID: "입금완료", INVOICED: "계산서발행", CANCELLED: "취소",
};
const STATUS_COLOR: Record<string, string> = {
  REQUESTED: "bg-amber-100 text-amber-700",
  APPROVED: "bg-blue-100 text-blue-700",
  INVOICED: "bg-violet-100 text-violet-700",
  PAID: "bg-emerald-100 text-emerald-700",
  CANCELLED: "bg-slate-100 text-slate-500",
};

export default function MyOrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  // 기본: 오늘부터 한 달 전 ~ 오늘
  const initial = (() => {
    const e = new Date(), s = new Date();
    s.setDate(s.getDate() - 30);
    const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    const defFrom = fmt(s), defTo = fmt(e);
    if (typeof window === "undefined") return { status: "", dateFrom: defFrom, dateTo: defTo };
    const q = new URLSearchParams(window.location.search);
    return {
      status: q.get("status") ?? "",
      dateFrom: q.has("dateFrom") ? (q.get("dateFrom") ?? "") : defFrom,
      dateTo:   q.has("dateTo")   ? (q.get("dateTo") ?? "")   : defTo,
    };
  })();
  const [status, setStatus] = useState(initial.status);
  const [dateFrom, setDateFrom] = useState(initial.dateFrom);
  const [dateTo, setDateTo] = useState(initial.dateTo);
  const [detail, setDetail] = useState<{ order: Order & { CEO_NAME?: string; BIZ_NO?: string; PHONE?: string; ADDRESS?: string; EMAIL?: string; MEMO?: string }; items: DetailLine[]; supplier: Supplier } | null>(null);

  const load = async () => {
    const res = await fetch("/api/m/orders/list", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        status: status || undefined,
        dateFrom: dateFrom || undefined,
        dateTo: dateTo || undefined,
      }),
    });
    const j = await res.json();
    setOrders(j.RESULTLIST ?? []);
  };

  // 검색조건 변경 시 즉시 자동 조회
  useEffect(() => { load(); }, [status, dateFrom, dateTo]); // eslint-disable-line react-hooks/exhaustive-deps

  const openDetail = async (o: Order) => {
    const res = await fetch("/api/m/orders/detail", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objid: o.OBJID }),
    });
    const j = await res.json();
    if (j.success) setDetail({ order: j.order, items: j.items, supplier: j.supplier });
  };

  const cancelOrder = async (o: Order) => {
    const ok = await Swal.fire({
      icon: "warning", title: "주문을 취소하시겠습니까?",
      text: o.ORDER_NO,
      showCancelButton: true, confirmButtonText: "취소", cancelButtonText: "닫기",
      confirmButtonColor: "#dc2626",
    });
    if (!ok.isConfirmed) return;
    const res = await fetch("/api/m/orders/cancel", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objid: o.OBJID }),
    });
    const j = await res.json();
    if (j.success) {
      Swal.fire({ icon: "success", title: "취소되었습니다", timer: 1200, showConfirmButton: false });
      setDetail(null);
      load();
    } else {
      Swal.fire({ icon: "error", title: "취소 실패", text: j.message });
    }
  };

  const onExport = () => {
    if (orders.length === 0) return;
    downloadXlsx("발주이력", orders, [
      { header: "발주번호", key: "ORDER_NO", width: 18 },
      { header: "발주일",   key: "ORDER_DATE", width: 12 },
      { header: "면세",     key: (r) => Number(r.TOTAL_TAXFREE), width: 14 },
      { header: "과세",     key: (r) => Number(r.TOTAL_TAXABLE), width: 14 },
      { header: "합계",     key: (r) => Number(r.TOTAL_AMOUNT), width: 14 },
      { header: "상태",     key: (r) => STATUS_LABEL[String(r.STATUS)] || String(r.STATUS), width: 10 },
    ]);
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold">내 발주 이력</h1>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">전체 {orders.length}건 — 행을 누르면 거래명세표가 열려요</p>
        </div>
        <div className="flex gap-2">
          <button onClick={onExport} disabled={orders.length === 0}
            className="inline-flex items-center gap-1.5 h-10 px-3 rounded-lg bg-emerald-700 text-white text-xs sm:text-sm font-bold hover:bg-emerald-800 disabled:opacity-50">
            <Download size={14} /> 엑셀
          </button>
          <Link href="/m/orders/new" className="px-3 sm:px-4 h-10 inline-flex items-center gap-2 rounded-lg bg-emerald-700 text-white text-xs sm:text-sm font-bold">
            새 발주
          </Link>
        </div>
      </div>

      <div className="flex gap-2 flex-wrap items-center">
        <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
          className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
        <span className="text-slate-400">~</span>
        <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)}
          className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
        <select value={status} onChange={(e) => setStatus(e.target.value)} className="h-10 px-3 rounded-lg border border-slate-200 text-sm">
          <option value="">전체 상태</option>
          {Object.entries(STATUS_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        {(dateFrom || dateTo || status) && (
          <button onClick={() => { setDateFrom(""); setDateTo(""); setStatus(""); }}
            className="h-10 px-3 rounded-lg border border-slate-200 text-slate-600 text-xs">초기화</button>
        )}
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="w-full text-sm min-w-[700px]">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <th className="text-left px-4 py-3 font-semibold">발주번호</th>
              <th className="text-left px-4 py-3 font-semibold">발주일</th>
              <th className="text-right px-4 py-3 font-semibold">면세</th>
              <th className="text-right px-4 py-3 font-semibold">과세</th>
              <th className="text-right px-4 py-3 font-semibold">합계</th>
              <th className="text-center px-4 py-3 font-semibold">상태</th>
            </tr>
          </thead>
          <tbody>
            {orders.length === 0 ? (
              <tr><td colSpan={6} className="text-center py-12 text-slate-400">발주 이력이 없습니다.</td></tr>
            ) : orders.map((o) => (
              <tr key={o.OBJID} className="border-t border-slate-100 hover:bg-emerald-50/40 cursor-pointer"
                  onClick={() => openDetail(o)}>
                <td className="px-4 py-3 font-semibold text-emerald-700">{o.ORDER_NO}</td>
                <td className="px-4 py-3">{o.ORDER_DATE}</td>
                <td className="px-4 py-3 text-right tabular-nums text-violet-700">{fmt(o.TOTAL_TAXFREE)}</td>
                <td className="px-4 py-3 text-right tabular-nums text-rose-700">{fmt(o.TOTAL_TAXABLE)}</td>
                <td className="px-4 py-3 text-right tabular-nums font-bold">₩{fmt(o.TOTAL_AMOUNT)}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs font-semibold ${STATUS_COLOR[o.STATUS]}`}>
                    {STATUS_LABEL[o.STATUS] || o.STATUS}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {detail && (
        <DetailModal
          order={detail.order}
          items={detail.items}
          supplier={detail.supplier}
          onClose={() => setDetail(null)}
          onCancel={() => cancelOrder(detail.order)}
          onReload={async () => {
            const res = await fetch("/api/m/orders/detail", {
              method: "POST", headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ objid: detail.order.OBJID }),
            });
            const j = await res.json();
            if (j.success) setDetail({ order: j.order, items: j.items, supplier: j.supplier });
            load();
          }}
        />
      )}
    </div>
  );
}

function DetailModal({ order, items, supplier, onClose, onCancel, onReload }: {
  order: Order & { CEO_NAME?: string; BIZ_NO?: string; PHONE?: string; ADDRESS?: string; EMAIL?: string };
  items: DetailLine[];
  supplier: Supplier;
  onClose: () => void;
  onCancel: () => void;
  onReload: () => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const editable = order.STATUS === "REQUESTED";

  const updateItemLine = async (lineObjid: string, qty: number) => {
    const res = await fetch("/api/m/orders/items/update", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ orderObjid: order.OBJID, lines: [{ objid: lineObjid, qty }] }),
    });
    const j = await res.json();
    if (j.success) onReload();
    else Swal.fire({ icon: "error", title: "수정 실패", text: j.message });
  };
  const deleteItemLine = async (lineObjid: string) => {
    const ok = await Swal.fire({ icon: "question", title: "이 품목을 주문에서 삭제하시겠습니까?", showCancelButton: true, confirmButtonText: "삭제", cancelButtonText: "취소", confirmButtonColor: "#dc2626" });
    if (!ok.isConfirmed) return;
    const res = await fetch("/api/m/orders/items/update", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ orderObjid: order.OBJID, lines: [{ objid: lineObjid, delete: true }] }),
    });
    const j = await res.json();
    if (j.success) onReload();
    else Swal.fire({ icon: "error", title: "삭제 실패", text: j.message });
  };

  const user = useAuthStore((s) => s.user);
  // 이미지 공유 버튼은 관리자(admin) 한해서만 노출. 일반 사용자(거래처) 화면에서는 숨김.
  const showImageShare = user?.isAdmin === true || user?.role === "ADMIN";

  const captureAndShare = async () => {
    if (!ref.current) return;
    await captureAndShareLib({
      node: ref.current,
      filename: `${order.ORDER_NO}_거래명세표`,
      shareTitle: `${order.ORDER_NO} 거래명세표`,
      shareText: order.COMPANY_NAME ?? "",
      forceWidth: 1100, // 엑셀 가로 출력처럼 펼쳐서 캡처
    });
  };

  return (
    <div className="fixed inset-0 bg-slate-900/60 z-50 flex items-center justify-center p-3" onClick={onClose}>
      <div className="bg-white rounded-xl shadow-xl max-w-3xl w-full max-h-[92vh] overflow-y-auto p-5" onClick={(e) => e.stopPropagation()}>
        <div className="flex justify-between items-center mb-3 print:hidden">
          <div className="flex gap-2">
            {showImageShare && (
              <button onClick={captureAndShare}
                className="inline-flex items-center gap-1 h-9 px-3 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold hover:bg-amber-200">
                <ImageIcon size={14} /> 이미지 공유
              </button>
            )}
            <a href={`/api/m/orders/statement/${order.OBJID}`}
              className="inline-flex items-center gap-1 h-9 px-3 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold hover:bg-emerald-200">
              <Download size={14} /> 엑셀 다운로드
            </a>
            {editable && (
              <button onClick={onCancel}
                className="inline-flex items-center gap-1 h-9 px-3 rounded-lg bg-rose-100 text-rose-700 text-xs font-bold hover:bg-rose-200">
                <Trash2 size={14} /> 주문 취소
              </button>
            )}
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-700 p-1.5">
            <X size={18} />
          </button>
        </div>

        <div ref={ref} className="bg-white p-3 text-[12px] text-slate-800">
          <div className="text-center">
            <h2 className="text-xl font-bold tracking-[0.3em] text-slate-900">거 래 명 세 표</h2>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-3 text-[11px]">
            <div>
              <div><b>발주번호</b> · {order.ORDER_NO}</div>
              <div><b>발주일자</b> · {order.ORDER_DATE}</div>
              <div><b>현재상태</b> · <span className="font-semibold">{STATUS_LABEL[order.STATUS] ?? order.STATUS}</span></div>
            </div>
            <table className="text-[11px] border border-slate-400 self-start ml-auto" style={{borderCollapse:'collapse'}}>
              <tbody>
                <tr>
                  <td rowSpan={3} className="border border-slate-400 bg-slate-700 text-white text-center font-bold px-2 py-1" style={{writingMode:'vertical-rl',textOrientation:'upright',width:'24px'}}>공급자</td>
                  <td className="border border-slate-400 bg-slate-100 text-center font-semibold px-2 py-1 whitespace-nowrap" style={{width:'110px'}}>결제 계좌</td>
                  <td className="border border-slate-400 px-3 py-1 font-bold whitespace-nowrap">{supplier.BANK_ACCOUNT}</td>
                </tr>
                <tr>
                  <td className="border border-slate-400 bg-slate-100 text-center font-semibold px-2 py-1">전화</td>
                  <td className="border border-slate-400 px-3 py-1">{supplier.PHONE}</td>
                </tr>
                <tr>
                  <td className="border border-slate-400 bg-slate-100 text-center font-semibold px-2 py-1">이메일</td>
                  <td className="border border-slate-400 px-3 py-1 text-blue-700">{supplier.EMAIL}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div className="border border-slate-200 rounded p-2 bg-slate-50/60 mt-3">
            <div className="font-semibold text-slate-900">{order.COMPANY_NAME} <span className="text-slate-500 font-normal">귀하</span></div>
            <div className="text-[11px] text-slate-600 mt-0.5">
              {order.CEO_NAME && <>대표: {order.CEO_NAME} · </>}
              {order.PHONE && <>전화: {order.PHONE}</>}
            </div>
          </div>

          {editable && (
            <p className="mt-3 text-[11px] text-amber-700 bg-amber-50 border border-amber-200 rounded p-2">
              ✏️ 출고요청 상태 — 품목 수량을 직접 고치거나 [×]로 삭제할 수 있어요. 저장은 자동.
            </p>
          )}
          <table className="w-full text-[11px] border border-slate-300 mt-2">
            <thead className="bg-slate-100">
              <tr>
                <th className="border border-slate-300 px-1.5 py-1.5 w-8">#</th>
                <th className="border border-slate-300 px-1.5 py-1.5 text-left">품명</th>
                <th className="border border-slate-300 px-1.5 py-1.5 w-12">구분</th>
                <th className="border border-slate-300 px-1.5 py-1.5 w-16">수량</th>
                <th className="border border-slate-300 px-1.5 py-1.5 w-20">단가</th>
                <th className="border border-slate-300 px-1.5 py-1.5">공급가</th>
                <th className="border border-slate-300 px-1.5 py-1.5">세액</th>
                <th className="border border-slate-300 px-1.5 py-1.5">합계</th>
                <th className="border border-slate-300 px-1.5 py-1.5 w-24">비고</th>
                {editable && <th className="border border-slate-300 px-1 py-1.5 w-8"></th>}
              </tr>
            </thead>
            <tbody className="tabular-nums">
              {items.map((it, idx) => {
                const isExtra = it.KIND === "DELIVERY" || it.KIND === "CHARTER";
                const kindBadge = it.KIND === "DELIVERY" ? "택배" : it.KIND === "CHARTER" ? "용차" : null;
                const kindBg = it.KIND === "DELIVERY" ? "bg-orange-50" : it.KIND === "CHARTER" ? "bg-sky-50" : "";
                const canEditItem = editable && !isExtra; // ITEM 라인만 본인이 수정 가능
                return (
                  <tr key={it.OBJID || idx} className={kindBg}>
                    <td className="border border-slate-300 px-1.5 py-1 text-center">{idx + 1}</td>
                    <td className="border border-slate-300 px-1.5 py-1">
                      {kindBadge && <span className={`mr-1 text-[9px] font-bold px-1 py-0.5 rounded ${it.KIND === "DELIVERY" ? "bg-orange-200 text-orange-800" : "bg-sky-200 text-sky-800"}`}>{kindBadge}</span>}
                      {isExtra ? (it.EXTRA_LABEL || it.ITEM_NAME) : it.ITEM_NAME}
                    </td>
                    <td className={`border border-slate-300 px-1.5 py-1 text-center ${it.IS_TAX_FREE === "Y" ? "text-violet-700" : "text-rose-700"}`}>
                      {it.IS_TAX_FREE === "Y" ? "면세" : "과세"}
                    </td>
                    <td className="border border-slate-300 px-1 py-0.5 text-right">
                      {canEditItem
                        ? <QtyInput initial={Number(it.QTY)} onSave={(q) => updateItemLine(it.OBJID, q)} />
                        : fmt(it.QTY)}
                    </td>
                    <td className="border border-slate-300 px-1.5 py-1 text-right">{fmt(it.UNIT_PRICE)}</td>
                    <td className="border border-slate-300 px-1.5 py-1 text-right">{fmt(it.SUPPLY_AMOUNT)}</td>
                    <td className="border border-slate-300 px-1.5 py-1 text-right">{it.IS_TAX_FREE === "Y" ? "-" : fmt(it.VAT_AMOUNT)}</td>
                    <td className="border border-slate-300 px-1.5 py-1 text-right font-semibold">{fmt(it.TOTAL_AMOUNT)}</td>
                    <td className="border border-slate-300 px-1.5 py-1 text-[10px] text-slate-600">{it.REMARK || ""}</td>
                    {editable && (
                      <td className="border border-slate-300 px-1 py-1 text-center">
                        {canEditItem
                          ? <button onClick={() => deleteItemLine(it.OBJID)} className="text-rose-500 hover:text-rose-700" title="삭제"><X size={12} /></button>
                          : <span className="text-slate-300 text-[10px]">자동</span>}
                      </td>
                    )}
                  </tr>
                );
              })}
            </tbody>
          </table>

          <table className="ml-auto text-[12px] tabular-nums mt-3">
            <tbody>
              <tr><td className="px-3 py-1 text-violet-700">면세 합계</td><td className="px-3 py-1 text-right min-w-[120px]">₩ {fmt(order.TOTAL_TAXFREE)}</td></tr>
              <tr><td className="px-3 py-1 text-rose-700">과세 공급가</td><td className="px-3 py-1 text-right">₩ {fmt(order.TOTAL_TAXABLE)}</td></tr>
              <tr><td className="px-3 py-1">세액 합계</td><td className="px-3 py-1 text-right">₩ {fmt(order.TOTAL_VAT)}</td></tr>
              <tr className="border-t-2 border-slate-900 font-bold">
                <td className="px-3 py-1.5 whitespace-nowrap text-[11px]">총 합계 (VAT포함)</td>
                <td className="px-3 py-1.5 text-right text-emerald-700 whitespace-nowrap">₩ {fmt(order.TOTAL_AMOUNT)}</td>
              </tr>
            </tbody>
          </table>
        </div>

        {editable && (
          <div className="mt-4 pt-3 border-t border-slate-200 text-[11px] text-amber-700 bg-amber-50 rounded p-2">
            ※ 출고요청 상태 — 품목 <b>수량 수정</b> · <b>품목 삭제</b> · <b>주문 취소</b> 모두 가능합니다. 택배/용차 라인은 모모 담당자가 조정합니다.
          </div>
        )}
      </div>
    </div>
  );
}

function QtyInput({ initial, onSave }: { initial: number; onSave: (qty: number) => void }) {
  const [v, setV] = useState(initial);
  useEffect(() => { setV(initial); }, [initial]);
  return (
    <input
      type="number"
      min={1}
      value={v}
      onChange={(e) => setV(Number(e.target.value))}
      onBlur={() => { if (v !== initial && v > 0) onSave(v); }}
      onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); }}
      className="w-full h-6 px-1 border border-slate-300 rounded text-[11px] text-right tabular-nums bg-white"
    />
  );
}
