"use client";

import React, { useState, useEffect, useCallback } from "react";
import { apiClient } from "@/lib/api/client";
import { DateRangePicker } from "./DateRangePicker";

export function AdjustHistory() {
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dateFrom, setDateFrom] = useState(() => {
    const d = new Date();
    d.setDate(d.getDate() - 30);
    return d.toISOString().slice(0, 10);
  });
  const [dateTo, setDateTo] = useState(() => new Date().toISOString().slice(0, 10));
  const [keyword, setKeyword] = useState("");

  const fetchHistory = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = {};
      if (dateFrom) params.date_from = dateFrom;
      if (dateTo) params.date_to = dateTo;
      if (keyword) params.item_code = keyword;
      const res = await apiClient.get("/pop/inventory/adjust-history", { params });
      setItems(res.data?.data || []);
    } catch {
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [dateFrom, dateTo, keyword]);

  useEffect(() => { fetchHistory(); }, [fetchHistory]);

  const filtered = items;

  return (
    <div className="flex flex-col h-full bg-white">
      {/* 필터 */}
      <div className="bg-white border-b border-gray-200 px-4 py-3 shrink-0">
        <div className="flex items-end gap-2">
          <div className="flex-1 grid grid-cols-1 sm:grid-cols-[auto_1fr] gap-2">
            <DateRangePicker
              from={dateFrom}
              to={dateTo}
              onChange={(f, t) => { setDateFrom(f); setDateTo(t); }}
            />
            <div>
              <label className="text-[10px] font-semibold text-gray-400 mb-1 block">품목검색</label>
              <input
                type="text"
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
                placeholder="품목코드 검색"
                className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-amber-400"
              />
            </div>
          </div>
          <button
            onClick={fetchHistory}
            className="px-5 py-2.5 rounded-lg bg-amber-500 text-white text-sm font-bold active:bg-amber-600 shrink-0"
          >
            조회
          </button>
        </div>
      </div>

      {/* KPI */}
      <div className="bg-white border-b border-gray-200 shrink-0">
        <div className="grid grid-cols-3 divide-x divide-gray-100">
          <div className="flex flex-col items-center py-3">
            <span className="text-xs font-bold text-gray-400">전체</span>
            <span className="text-2xl font-extrabold text-gray-900">{filtered.length}</span>
          </div>
          <div className="flex flex-col items-center py-3">
            <span className="text-xs font-bold text-gray-400">확인</span>
            <span className="text-2xl font-extrabold text-green-600">
              {filtered.filter((h: any) => h.transaction_type === "조정확인").length}
            </span>
          </div>
          <div className="flex flex-col items-center py-3">
            <span className="text-xs font-bold text-gray-400">조정</span>
            <span className="text-2xl font-extrabold text-amber-600">
              {filtered.filter((h: any) => h.transaction_type === "조정").length}
            </span>
          </div>
        </div>
      </div>

      {/* 리스트 */}
      <div className="flex-1 overflow-y-auto">
        <div className="flex items-center justify-between px-4 py-2 bg-gray-50 border-b border-gray-200">
          <span className="text-sm font-bold text-gray-600">조정 이력</span>
          <span className="text-sm text-gray-400">총 {filtered.length}건</span>
        </div>

        {loading ? (
          <div className="flex justify-center py-16">
            <div className="w-10 h-10 border-4 border-amber-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-gray-400">
            <span className="text-5xl mb-3">📋</span>
            <p className="text-lg font-semibold">조정 이력이 없습니다</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {filtered.map((h: any) => {
              const isConfirm = h.transaction_type === "조정확인";
              const qty = parseFloat(h.quantity || "0");
              return (
                <div key={h.id} className={`flex items-center gap-3 px-4 py-4 ${isConfirm ? "bg-white" : "bg-amber-50/50"}`}>
                  <div className={`w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl shrink-0 ${
                    isConfirm ? "bg-green-500" : "bg-amber-500"
                  }`}>
                    {isConfirm ? "✓" : "~"}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-lg font-bold text-gray-900">{h.item_code}</p>
                    <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                      {h.reason && (
                        <span className={`text-sm px-2.5 py-0.5 rounded-lg font-bold ${
                          isConfirm ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"
                        }`}>{h.reason}</span>
                      )}
                      <span className="text-sm text-gray-400">{h.warehouse_code}</span>
                      <span className="text-sm text-gray-400">{h.manager_name || h.writer}</span>
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    <p className={`text-xl font-bold ${qty === 0 ? "text-green-600" : qty > 0 ? "text-blue-600" : "text-red-600"}`}>
                      {qty === 0 ? "이상없음" : (qty > 0 ? `+${qty}` : qty)}
                    </p>
                    {h.system_qty != null && qty !== 0 && (
                      <p className="text-sm text-gray-400">{h.system_qty} → {h.actual_qty ?? h.system_qty}</p>
                    )}
                    <p className="text-xs text-gray-400 mt-0.5">
                      {h.transaction_date ? new Date(h.transaction_date).toLocaleDateString() : ""}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
