"use client";

import { useState, useEffect } from "react";
import { X } from "lucide-react";
import { fetchApi } from "../utils/fetch";

export default function ExchangeForm({
  currentUser,
  setCurrentUser,
  item,
  onClose,
  setAlert,
}) {
  const [formData, setFormData] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (currentUser && currentUser.account) {
      setFormData((prevData) => ({
        ...prevData,
        account: currentUser.account,
      }));
    }
  }, []);

  const handleInputChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      const params = {
        userId: currentUser.id,
        username: currentUser.username,
        item,
        status: "待兑换未审核",
        exchangeInfo: {
          account: formData.account || "",
          address: formData.address || "",
          name: formData.name || "",
          phone: formData.phone || "",
        },
        exchangeTime: new Date(), // 添加兑换时间
        // exchangeCount: formData.exchangeCount || 1,
      };

      // console.log("params", params);

      const res = await fetchApi("/api/exchange-history", {
        method: "POST",
        body: JSON.stringify(params),
      });

      if (res.success) {
        setAlert({
          type: "success",
          message: "提交成功，正在审核中",
        });
        onClose();
        const updatedUser = {
          ...currentUser,
          points: currentUser.points - item.points,
          account: formData.account || currentUser.account,
        };
        localStorage.setItem("currentUser", JSON.stringify(updatedUser));
        setCurrentUser(updatedUser);


      } else {
        setAlert({ type: "error", message: res.error });
      }
    } catch (error) {
      console.error("兑换请求失败:", error);
      setAlert({ type: "error", message: res.error });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white text-black rounded-lg max-w-md w-full mx-4">
        <div className="flex justify-end items-center p-4">
          <button
            onClick={onClose}
            className="text-gray-600 hover:text-gray-800 transition duration-300"
            aria-label="关闭"
          >
            <X size={24} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="px-4 pb-4">
          {item.type === "彩金" || item.type === "优惠券" ? (
            <div className="mb-4">
              <label htmlFor="account" className="block mb-2 font-semibold">
                兑换账号
              </label>
              <input
                type="text"
                id="account"
                name="account"
                placeholder="请输入智博1919账号"
                required
                className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                onChange={handleInputChange}
                value={formData.account || ""}
              />
            </div>
          ) : (
            <>
              <div className="mb-4">
                <label htmlFor="name" className="block mb-2 font-semibold">
                  姓名
                </label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  required
                  className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  onChange={handleInputChange}
                />
              </div>
              <div className="mb-4">
                <label htmlFor="phone" className="block mb-2 font-semibold">
                  电话
                </label>
                <input
                  type="tel"
                  id="phone"
                  name="phone"
                  required
                  className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  onChange={handleInputChange}
                />
              </div>
              <div className="mb-4">
                <label htmlFor="address" className="block mb-2 font-semibold">
                  地址
                </label>
                <textarea
                  id="address"
                  name="address"
                  required
                  className="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  onChange={handleInputChange}
                ></textarea>
              </div>
            </>
          )}
          <div className="flex justify-end mt-6">
            <button
              type="button"
              onClick={onClose}
              className="mr-4 px-4 py-2 border rounded text-gray-600 hover:bg-gray-100 transition duration-300"
              disabled={isSubmitting}
            >
              取消
            </button>
            <button
              type="submit"
              className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition duration-300"
              disabled={isSubmitting}
            >
              {isSubmitting ? "提交中..." : "确认兑换"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
