// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/Me/BlockedUsers.jsx
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import Navigation from "../../../components/Navigation";
import Page from "../../../components/Page";
import { GetBlockedEmails, AddBlockedEmail, RemoveBlockedEmail } from "../../../../wailsjs/go/app/Application";

function BlockedUsers() {
  const [blockedEmails, setBlockedEmails] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  // Add form state
  const [newEmail, setNewEmail] = useState("");
  const [addLoading, setAddLoading] = useState(false);
  const [addError, setAddError] = useState("");

  // Delete state
  const [deleteLoading, setDeleteLoading] = useState("");

  useEffect(() => {
    // Wait for Wails runtime to be ready
    let attempts = 0;
    const maxAttempts = 50;
    let isCancelled = false;

    const checkWailsReady = () => {
      if (isCancelled) return;

      if (window.go && window.go.app && window.go.app.Application) {
        loadBlockedEmails();
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkWailsReady, 100);
      } else {
        if (!isCancelled) {
          setIsLoading(false);
          setError("Failed to initialize. Please refresh the page.");
        }
      }
    };

    checkWailsReady();

    return () => {
      isCancelled = true;
    };
  }, []);

  const loadBlockedEmails = async () => {
    try {
      setIsLoading(true);
      setError("");

      if (!window.go || !window.go.app || !window.go.app.Application) {
        throw new Error("Application not ready");
      }

      console.log("Loading blocked emails...");
      const emails = await GetBlockedEmails();
      console.log("Blocked emails loaded:", emails);

      setBlockedEmails(emails || []);
    } catch (err) {
      console.error("Failed to load blocked emails:", err);
      setError(err.message || "Failed to load blocked users");
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddEmail = async (e) => {
    e.preventDefault();
    if (!newEmail.trim()) return;

    setAddLoading(true);
    setAddError("");
    setSuccess("");

    try {
      console.log("Adding blocked email:", newEmail);
      await AddBlockedEmail(newEmail.trim(), "Blocked via UI");
      setSuccess(`${newEmail} has been blocked successfully.`);
      setNewEmail("");
      await loadBlockedEmails();
    } catch (err) {
      console.error("Failed to add blocked email:", err);
      setAddError(err.message || "Failed to block email");
    } finally {
      setAddLoading(false);
    }
  };

  const handleRemoveEmail = async (email) => {
    setDeleteLoading(email);
    setError("");
    setSuccess("");

    try {
      console.log("Removing blocked email:", email);
      await RemoveBlockedEmail(email);
      setSuccess(`${email} has been unblocked.`);
      await loadBlockedEmails();
    } catch (err) {
      console.error("Failed to remove blocked email:", err);
      setError(err.message || "Failed to unblock email");
    } finally {
      setDeleteLoading("");
    }
  };

  const formatDate = (dateString) => {
    if (!dateString) return "N/A";
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return "Invalid Date";
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });
    } catch (error) {
      return "Invalid Date";
    }
  };

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Blocked Users">
          {/* Breadcrumb */}
          <div style={{ marginBottom: "20px", fontSize: "14px", color: "#6b7280" }}>
            <Link to="/dashboard" style={{ color: "#3b82f6", textDecoration: "none" }}>Dashboard</Link>
            <span style={{ margin: "0 8px" }}>›</span>
            <Link to="/me" style={{ color: "#3b82f6", textDecoration: "none" }}>My Profile</Link>
            <span style={{ margin: "0 8px" }}>›</span>
            <span style={{ color: "#2c3e50", fontWeight: "500" }}>Blocked Users</span>
          </div>

          {/* Header */}
          <div style={{
            background: "white",
            padding: "30px",
            borderRadius: "12px",
            marginBottom: "20px",
            boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
          }}>
            <div style={{ display: "flex", alignItems: "center" }}>
              <div style={{
                width: "50px",
                height: "50px",
                borderRadius: "12px",
                background: "#fee2e2",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                marginRight: "15px",
              }}>
                <span style={{ fontSize: "24px" }}>🚫</span>
              </div>
              <div>
                <h1 style={{ margin: 0, color: "#2c3e50", fontSize: "24px" }}>Blocked Users</h1>
                <p style={{ margin: "5px 0 0 0", color: "#7f8c8d" }}>
                  Manage users who cannot share folders with you
                </p>
              </div>
            </div>
          </div>

          {/* Success message */}
          {success && (
            <div style={{
              marginBottom: "20px",
              padding: "15px",
              background: "#d4edda",
              border: "1px solid #c3e6cb",
              borderRadius: "8px",
              display: "flex",
              alignItems: "center",
            }}>
              <span style={{ fontSize: "20px", marginRight: "10px" }}>✓</span>
              <p style={{ margin: 0, color: "#155724" }}>{success}</p>
            </div>
          )}

          {/* Error message */}
          {error && (
            <div style={{
              marginBottom: "20px",
              padding: "15px",
              background: "#f8d7da",
              border: "1px solid #f5c6cb",
              borderRadius: "8px",
              display: "flex",
              alignItems: "center",
            }}>
              <span style={{ fontSize: "20px", marginRight: "10px" }}>⚠️</span>
              <p style={{ margin: 0, color: "#721c24" }}>{error}</p>
            </div>
          )}

          {/* Add Email Form */}
          <div style={{
            background: "white",
            padding: "30px",
            borderRadius: "12px",
            marginBottom: "20px",
            boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
          }}>
            <h2 style={{ marginTop: 0, color: "#2c3e50", fontSize: "18px" }}>Block a User</h2>
            <p style={{ color: "#7f8c8d", fontSize: "14px", marginBottom: "15px" }}>
              Enter the email address of a user you want to block. They will not be able to share folders with you.
            </p>

            <form onSubmit={handleAddEmail} style={{ display: "flex", gap: "10px" }}>
              <div style={{ flex: 1 }}>
                <input
                  type="email"
                  value={newEmail}
                  onChange={(e) => {
                    setNewEmail(e.target.value);
                    if (addError) setAddError("");
                  }}
                  placeholder="Enter email address to block"
                  style={{
                    width: "100%",
                    padding: "10px",
                    borderRadius: "8px",
                    border: "1px solid #ddd",
                    fontSize: "14px",
                  }}
                  disabled={addLoading}
                  required
                />
                {addError && (
                  <p style={{ margin: "5px 0 0 0", fontSize: "14px", color: "#e74c3c" }}>{addError}</p>
                )}
              </div>
              <button
                type="submit"
                className="nav-button"
                disabled={addLoading || !newEmail.trim()}
                style={{ whiteSpace: "nowrap" }}
              >
                {addLoading ? "Adding..." : "➕ Block"}
              </button>
            </form>
          </div>

          {/* Blocked Emails List */}
          <div style={{
            background: "white",
            padding: "30px",
            borderRadius: "12px",
            boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
          }}>
            <h2 style={{ marginTop: 0, color: "#2c3e50", fontSize: "18px" }}>
              Blocked Users ({blockedEmails.length})
            </h2>

            {isLoading ? (
              <div style={{ textAlign: "center", padding: "40px" }}>
                <p style={{ color: "#7f8c8d" }}>Loading blocked users...</p>
              </div>
            ) : blockedEmails.length === 0 ? (
              <div style={{ textAlign: "center", padding: "40px" }}>
                <span style={{ fontSize: "48px" }}>🚫</span>
                <p style={{ color: "#7f8c8d", margin: "10px 0 0 0" }}>No blocked users</p>
                <p style={{ fontSize: "14px", color: "#95a5a6", margin: "5px 0 0 0" }}>
                  Users you block won't be able to share folders with you.
                </p>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                {blockedEmails.map((blocked) => (
                  <div
                    key={blocked.blocked_email}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      padding: "15px",
                      background: "#f8f9fa",
                      borderRadius: "8px",
                      border: "1px solid #e9ecef",
                    }}
                  >
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <span style={{ fontSize: "20px", marginRight: "12px" }}>✉️</span>
                      <div>
                        <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>
                          {blocked.blocked_email}
                        </p>
                        <p style={{ margin: "3px 0 0 0", fontSize: "12px", color: "#7f8c8d" }}>
                          Blocked on {formatDate(blocked.created_at)}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() => handleRemoveEmail(blocked.blocked_email)}
                      className="nav-button danger"
                      disabled={deleteLoading === blocked.blocked_email}
                      style={{ whiteSpace: "nowrap" }}
                    >
                      {deleteLoading === blocked.blocked_email ? "Removing..." : "🗑️ Unblock"}
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Info section */}
          <div style={{
            marginTop: "20px",
            padding: "20px",
            background: "#e3f2fd",
            border: "1px solid #bbdefb",
            borderRadius: "8px",
          }}>
            <h3 style={{ marginTop: 0, fontSize: "16px", color: "#1565c0" }}>
              How blocking works
            </h3>
            <ul style={{ margin: 0, paddingLeft: "20px", color: "#1976d2", fontSize: "14px" }}>
              <li>Blocked users cannot share folders or files with you</li>
              <li>You can still share folders with blocked users</li>
              <li>Blocking is private - users are not notified when blocked</li>
              <li>Existing shares are not affected when you block someone</li>
            </ul>
          </div>
        </Page>
      </div>
    </div>
  );
}

export default BlockedUsers;
