import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { FiUpload, FiLoader, FiCheckCircle, FiUsers } from "react-icons/fi";
import { uploadDocument, getAllUsers, getUserInfo } from "../../services/api";
import { Card } from "../UI/Card";

function DocumentUpload() {
  const [file, setFile] = useState(null);
  const [title, setTitle] = useState("");
  const [selectedUserId, setSelectedUserId] = useState(""); // Changed from array to single value
  const [availableUsers, setAvailableUsers] = useState([]);
  const [status, setStatus] = useState("idle");
  const [errorMessage, setErrorMessage] = useState("");
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    fetchUsers();
    getCurrentUser();
  }, []);

  const getCurrentUser = async () => {
    try {
      const response = await getUserInfo();
      setCurrentUser(response.data);
    } catch (error) {
      console.error("Failed to get current user:", error);
      setErrorMessage("Failed to get current user info");
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await getAllUsers();
      setAvailableUsers(response.data.filter((user) => !user.isAdmin));
    } catch (error) {
      setErrorMessage("Failed to load users");
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!file || !title || !selectedUserId || !currentUser?.id) {
      setErrorMessage("Please provide all required information");
      return;
    }

    // Convert IDs to numbers
    const sharedWithId = parseInt(selectedUserId, 10);
    const uploadedById = parseInt(currentUser.id, 10);

    if (isNaN(sharedWithId) || isNaN(uploadedById)) {
      setErrorMessage("Invalid user IDs");
      return;
    }

    setStatus("uploading");
    setErrorMessage("");

    const formData = new FormData();
    formData.append("file", file);
    formData.append("title", title);
    formData.append("sharedWithId", sharedWithId);
    formData.append("uploadedById", uploadedById);

    // Debug log
    // console.log("Form Data:", {
    //   title,
    //   sharedWithId,
    //   uploadedById,
    //   fileName: file.name,
    // });

    try {
      await uploadDocument(formData);
      setStatus("completed");
      setTitle("");
      setFile(null);
      setSelectedUserId("");
      event.target.reset();
    } catch (error) {
      console.error("Upload error:", error);
      setStatus("failed");
      setErrorMessage(error.response?.data?.message || "Upload failed");
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-900 to-primary-800 p-6">
      <div className="max-w-4xl mx-auto">
        <header className="mb-8 mt-20">
          <h1 className="text-3xl font-bold text-white mb-2">
            Сподели документ
          </h1>
          {/* <p className="text-neutral-400">Share documents with your clients</p> */}
        </header>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          <Card className="bg-neutral-900/80 backdrop-blur-lg border border-neutral-800">
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Title Input */}
              <div>
                <label className="block text-sm font-medium text-white mb-4">
                  Наслов на документот
                </label>
                <input
                  type="text"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  className="w-full px-4 py-2 rounded-lg bg-neutral-800/50 border border-neutral-700
                    text-white placeholder-neutral-400 focus:outline-none focus:border-primary-500"
                  required
                />
              </div>

              {/* File Input */}
              <div>
                <label className="block text-sm font-medium text-white mb-2">
                  Документ
                </label>
                <div className="flex items-center justify-center w-full">
                  <label
                    className="w-full flex flex-col items-center px-4 py-6 rounded-lg
                    border-2 border-dashed border-neutral-700 hover:border-primary-500
                    cursor-pointer transition-colors"
                  >
                    <FiUpload className="w-8 h-8 text-neutral-400" />
                    <span className="mt-2 text-sm text-neutral-400">
                      {file ? file.name : "Избери документ"}
                    </span>
                    <input
                      type="file"
                      className="hidden"
                      onChange={(e) => setFile(e.target.files[0])}
                      required
                    />
                  </label>
                </div>
              </div>

              {/* User Selection */}
              <div>
                <label className="block text-sm font-medium text-white mb-2">
                  Сподели со
                </label>
                <div className="relative">
                  <FiUsers className="absolute top-3 left-3 text-neutral-400" />
                  <select
                    value={selectedUserId}
                    onChange={(e) => setSelectedUserId(e.target.value)}
                    className="w-full pl-10 px-4 py-2 rounded-lg bg-neutral-800/50 border border-neutral-700
                      text-white focus:outline-none focus:border-primary-500"
                    required
                  >
                    <option value="">Избери корисник</option>
                    {availableUsers.map((user) => (
                      <option key={user.id} value={user.id}>
                        {user.name} ({user.email})
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Error Message */}
              {errorMessage && (
                <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-200">
                  {errorMessage}
                </div>
              )}

              {/* Success Message */}
              {status === "completed" && (
                <div className="p-4 bg-green-500/10 border border-green-500/20 rounded-lg text-green-200">
                  Документот успешно е споделен!
                </div>
              )}

              {/* Submit Button */}
              <button
                type="submit"
                disabled={status === "uploading"}
                className="w-full flex items-center justify-center px-4 py-2 rounded-lg
                  bg-primary-600 hover:bg-primary-700 text-white font-medium
                  transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {status === "uploading" ? (
                  <>
                    <FiLoader className="w-5 h-5 mr-2 animate-spin" />
                    Uploading...
                  </>
                ) : status === "completed" ? (
                  <>
                    <FiCheckCircle className="w-5 h-5 mr-2" />
                    Upload Complete
                  </>
                ) : (
                  "Прикачи"
                )}
              </button>
            </form>
          </Card>
        </motion.div>
      </div>
    </div>
  );
}

export default DocumentUpload;
