"use client";

import { useState, useEffect } from "react";
import toast from "react-hot-toast";
import { UserFormProps } from "@/lib/api/types/user.types";
import { createUser, updateUser, getUserById } from "@/lib/api/user.api";

const overlayStyle: React.CSSProperties = {
  position: "fixed", inset: 0,
  background: "rgba(0,0,0,0.55)", backdropFilter: "blur(4px)",
  zIndex: 9999, display: "flex", alignItems: "center",
  justifyContent: "center", padding: 20,
};

const modalStyle: React.CSSProperties = {
  background: "#fff", borderRadius: 18, width: "100%",
  maxWidth: 480, maxHeight: "90vh", overflowY: "auto",
  boxShadow: "0 24px 64px rgba(0,0,0,0.18)",
  animation: "slideUp 0.2s cubic-bezier(0.16,1,0.3,1)",
};

const inputStyle: React.CSSProperties = {
  width: "100%", padding: "10px 13px",
  border: "1px solid #e5e7eb", borderRadius: 9,
  fontSize: 13, outline: "none", background: "#fafafa",
  fontFamily: "inherit", boxSizing: "border-box",
  transition: "border-color 0.15s, box-shadow 0.15s",
};

const labelStyle: React.CSSProperties = {
  display: "block", fontSize: 10, fontWeight: 700,
  color: "#6b7280", textTransform: "uppercase",
  letterSpacing: "0.5px", marginBottom: 5,
};

export default function UserForm({ isOpen, onClose, refreshData, userId }: UserFormProps) {
  const isEdit = !!userId;

  const [form, setForm] = useState({
    firstName: "", lastName: "", email: "", password: "",
  });
  const [saving, setSaving] = useState(false);
  const [loadingUser, setLoadingUser] = useState(false);

  // Load user for edit mode
  useEffect(() => {
    if (isEdit && userId) {
      setLoadingUser(true);
      getUserById(userId)
        .then((data) => {
          setForm({
            firstName: data.firstName || "",
            lastName: data.lastName || "",
            email: data.email || "",
            password: "",
          });
        })
        .catch((err) => toast.error(err.message))
        .finally(() => setLoadingUser(false));
    }
  }, [userId, isEdit]);

  const handleSubmit = async () => {
    if (!form.firstName.trim()) { toast.error("First name is required"); return; }
    if (!form.email.trim() || !form.email.includes("@")) { toast.error("Valid email is required"); return; }
    if (!isEdit && form.password.length < 8) { toast.error("Password must be at least 8 characters"); return; }

    setSaving(true);
    try {
      if (isEdit && userId) {
        await updateUser(userId, {
          firstName: form.firstName,
          lastName: form.lastName,
          email: form.email,
          password: form.password || undefined,
        });
        toast.success("User updated successfully!");
      } else {
        await createUser({
          firstName: form.firstName,
          lastName: form.lastName,
          email: form.email,
          password: form.password,
        });
        toast.success("User created! OTP verification email sent.");
      }
      onClose();
      refreshData?.();
    } catch (err: any) {
      toast.error(err.message || "Failed to save user");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  const onFocus = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.style.borderColor = "#8b14d4";
    e.target.style.boxShadow = "0 0 0 3px rgba(139,20,212,0.08)";
  };
  const onBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.style.borderColor = "#e5e7eb";
    e.target.style.boxShadow = "none";
  };

  return (
    <div style={overlayStyle} onClick={onClose}>
      <style>{`@keyframes slideUp{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}`}</style>
      <div style={modalStyle} onClick={(e) => e.stopPropagation()}>

        {/* Header */}
        <div style={{
          padding: "20px 22px 16px", borderBottom: "1px solid #f3f4f6",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          background: "linear-gradient(135deg,rgba(139,20,212,0.04),rgba(121,4,194,0.06))",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{
              width: 40, height: 40, borderRadius: 12, flexShrink: 0,
              background: "linear-gradient(135deg,#8b14d4,#6d0fa6)",
              display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18,
            }}>
              {isEdit ? "✏️" : "👤"}
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 700, color: "#111827" }}>
                {isEdit ? "Edit User" : "Create New User"}
              </div>
              <div style={{ fontSize: 12, color: "#9ca3af", marginTop: 1 }}>
                {isEdit
                  ? "Update user information"
                  : "New user will receive an OTP verification email"}
              </div>
            </div>
          </div>
          <button onClick={onClose} style={{
            background: "none", border: "none", fontSize: 22,
            cursor: "pointer", color: "#9ca3af", padding: "4px 8px", borderRadius: 8,
          }}>×</button>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
          {loadingUser ? (
            <div style={{ textAlign: "center", padding: 40, color: "#9ca3af" }}>Loading...</div>
          ) : (
            <>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <label style={labelStyle}>
                    First Name <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <input
                    style={inputStyle} placeholder="John"
                    value={form.firstName}
                    onChange={(e) => setForm({ ...form, firstName: e.target.value })}
                    onFocus={onFocus} onBlur={onBlur}
                  />
                </div>
                <div>
                  <label style={labelStyle}>Last Name</label>
                  <input
                    style={inputStyle} placeholder="Doe"
                    value={form.lastName}
                    onChange={(e) => setForm({ ...form, lastName: e.target.value })}
                    onFocus={onFocus} onBlur={onBlur}
                  />
                </div>
              </div>

              <div>
                <label style={labelStyle}>
                  Email Address <span style={{ color: "#ef4444" }}>*</span>
                </label>
                <input
                  style={inputStyle} type="email" placeholder="john@company.com"
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  onFocus={onFocus} onBlur={onBlur}
                />
              </div>

              <div>
                <label style={labelStyle}>
                  Password{" "}
                  {isEdit ? (
                    <span style={{ color: "#d1d5db", fontWeight: 400, textTransform: "none", fontSize: 9 }}>
                      (leave blank to keep current)
                    </span>
                  ) : (
                    <span style={{ color: "#ef4444" }}>*</span>
                  )}
                </label>
                <input
                  style={inputStyle} type="password"
                  placeholder={isEdit ? "New password..." : "Min 8 characters"}
                  value={form.password}
                  onChange={(e) => setForm({ ...form, password: e.target.value })}
                  onFocus={onFocus} onBlur={onBlur}
                />
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: "14px 22px", borderTop: "1px solid #f3f4f6",
          display: "flex", gap: 8, justifyContent: "flex-end",
        }}>
          <button onClick={onClose} style={{
            padding: "9px 18px", borderRadius: 9, border: "1px solid #e5e7eb",
            background: "#fff", color: "#6b7280", fontSize: 13, fontWeight: 600, cursor: "pointer",
          }}>
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving || loadingUser}
            style={{
              padding: "9px 20px", borderRadius: 9, border: "none",
              background: "linear-gradient(135deg,#8b14d4,#6d0fa6)",
              color: "#fff", fontSize: 13, fontWeight: 700,
              cursor: (saving || loadingUser) ? "not-allowed" : "pointer",
              opacity: (saving || loadingUser) ? 0.6 : 1,
              boxShadow: "0 4px 12px rgba(139,20,212,0.25)",
            }}
          >
            {saving ? "Saving..." : isEdit ? "Save Changes" : "Create User"}
          </button>
        </div>
      </div>
    </div>
  );
}
