// File: src/pages/User/Me/BlockedUsers.jsx
import React, { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate } from "react-router";
import { useAuth } from "../../../services/Services";
import withPasswordProtection from "../../../hocs/withPasswordProtection";
import Layout from "../../../components/Layout/Layout";
import BlockedEmailManager from "../../../services/Manager/BlockedEmailManager";
import {
  Button,
  Input,
  Alert,
  Card,
  Breadcrumb,
  Spinner,
  useUIXTheme,
} from "../../../components/UIX";
import {
  NoSymbolIcon,
  PlusIcon,
  TrashIcon,
  ArrowLeftIcon,
  EnvelopeIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

const BlockedUsers = () => {
  const navigate = useNavigate();
  const { authManager } = useAuth();
  const { getThemeClasses } = useUIXTheme();
  const isMountedRef = useRef(true);

  // Page state
  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("");

  // Manager instance
  const [blockedEmailManager, setBlockedEmailManager] = useState(null);

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Initialize manager
  useEffect(() => {
    if (authManager) {
      const manager = new BlockedEmailManager(authManager);
      manager.initialize();
      setBlockedEmailManager(manager);
    }
  }, [authManager]);

  // Load blocked emails
  const loadBlockedEmails = useCallback(async () => {
    if (!blockedEmailManager) return;

    setIsLoading(true);
    setError("");

    try {
      if (import.meta.env.DEV) {
        console.log("[BlockedUsers] Loading blocked emails...");
      }
      const emails = await blockedEmailManager.getBlockedEmails(true);
      if (!isMountedRef.current) return;
      setBlockedEmails(emails);
      if (import.meta.env.DEV) {
        console.log("[BlockedUsers] Loaded", emails.length, "blocked emails");
      }
    } catch (err) {
      if (!isMountedRef.current) return;
      if (import.meta.env.DEV) {
        console.error("[BlockedUsers] Failed to load blocked emails:", err);
      }
      setError(err.message || "Failed to load blocked users.");
    } finally {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
    }
  }, [blockedEmailManager]);

  useEffect(() => {
    if (blockedEmailManager && authManager?.isAuthenticated()) {
      loadBlockedEmails();
    }
  }, [blockedEmailManager, authManager, loadBlockedEmails]);

  // Handle add email
  const handleAddEmail = useCallback(async (e) => {
    e.preventDefault();
    if (!newEmail.trim() || !isMountedRef.current) return;

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

    try {
      if (import.meta.env.DEV) {
        console.log("[BlockedUsers] Adding email to blocked list:", newEmail);
      }
      await blockedEmailManager.addBlockedEmail(newEmail.trim());
      if (!isMountedRef.current) return;
      setSuccess(`${newEmail} has been blocked successfully.`);
      setNewEmail("");
      await loadBlockedEmails();
    } catch (err) {
      if (!isMountedRef.current) return;
      if (import.meta.env.DEV) {
        console.error("[BlockedUsers] Failed to add blocked email:", err);
      }
      setAddError(err.message || "Failed to block email.");
    } finally {
      if (isMountedRef.current) {
        setAddLoading(false);
      }
    }
  }, [newEmail, blockedEmailManager, loadBlockedEmails]);

  // Handle remove email
  const handleRemoveEmail = useCallback(async (email) => {
    if (!isMountedRef.current) return;

    setDeleteLoading(email);
    setError("");
    setSuccess("");

    try {
      if (import.meta.env.DEV) {
        console.log("[BlockedUsers] Removing email from blocked list:", email);
      }
      await blockedEmailManager.removeBlockedEmail(email);
      if (!isMountedRef.current) return;
      setSuccess(`${email} has been unblocked.`);
      await loadBlockedEmails();
    } catch (err) {
      if (!isMountedRef.current) return;
      if (import.meta.env.DEV) {
        console.error("[BlockedUsers] Failed to remove blocked email:", err);
      }
      setError(err.message || "Failed to unblock email.");
    } finally {
      if (isMountedRef.current) {
        setDeleteLoading("");
      }
    }
  }, [blockedEmailManager, loadBlockedEmails]);

  // Breadcrumb items
  const breadcrumbItems = [
    { label: "Settings", to: "/me", icon: Cog6ToothIcon },
    { label: "Blocked Users", isActive: true, icon: NoSymbolIcon },
  ];

  return (
    <Layout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb Navigation */}
        <Breadcrumb items={breadcrumbItems} />

        {/* Main Card */}
        <Card>
          {/* Header */}
          <div className={`p-6 border-b ${getThemeClasses("border-secondary")}`}>
            <div className="flex flex-col space-y-4 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
              <div className="flex-1 min-w-0">
                <div className="flex items-start">
                  <div className="p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 bg-red-500">
                    <NoSymbolIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      Blocked Users
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Manage users who cannot share folders with you
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0">
                <Button
                  onClick={() => navigate("/me")}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back to Settings</span>
                  </span>
                </Button>
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="px-6 pt-6">
            {success && (
              <Alert type="success" className="mb-4" onClose={() => setSuccess("")}>
                {success}
              </Alert>
            )}
            {error && (
              <Alert type="error" className="mb-4" onClose={() => setError("")}>
                {error}
              </Alert>
            )}
          </div>

          {/* Content */}
          <div className="px-6 pb-6 pt-2">
            {/* Add Email Form */}
            <Card className={`border ${getThemeClasses("border-muted")} p-6 mb-6`}>
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4`}>
                Block a User
              </h2>
              <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
                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} className="flex gap-3">
                <div className="flex-1">
                  <Input
                    type="email"
                    name="block_email"
                    value={newEmail}
                    onChange={(value) => {
                      setNewEmail(value);
                      if (addError) setAddError("");
                    }}
                    placeholder="Enter email address to block"
                    disabled={addLoading}
                    required
                    error={addError}
                    icon={EnvelopeIcon}
                  />
                </div>
                <Button
                  type="submit"
                  variant="primary"
                  disabled={addLoading || !newEmail.trim()}
                  loading={addLoading}
                >
                  {!addLoading && (
                    <span className="inline-flex items-center gap-2">
                      <PlusIcon className="h-4 w-4" />
                      <span>Block</span>
                    </span>
                  )}
                  {addLoading && "Adding..."}
                </Button>
              </form>
            </Card>

            {/* Blocked Emails List */}
            <Card className={`border ${getThemeClasses("border-muted")} p-6`}>
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4`}>
                Blocked Users ({blockedEmails.length})
              </h2>

              {isLoading ? (
                <div className="flex items-center justify-center py-8">
                  <div className="text-center">
                    <Spinner size="lg" className="mx-auto mb-4" />
                    <p className={getThemeClasses("text-secondary")}>Loading blocked users...</p>
                  </div>
                </div>
              ) : blockedEmails.length === 0 ? (
                <div className="text-center py-8">
                  <NoSymbolIcon className={`h-12 w-12 ${getThemeClasses("text-secondary")} mx-auto mb-4`} />
                  <p className={getThemeClasses("text-secondary")}>No blocked users</p>
                  <p className={`text-sm ${getThemeClasses("text-secondary")} mt-1`}>
                    Users you block won't be able to share folders with you.
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {blockedEmails.map((blocked) => (
                    <div
                      key={blocked.blocked_email}
                      className={`flex items-center justify-between p-4 ${getThemeClasses("bg-muted")} rounded-lg border ${getThemeClasses("border-muted")}`}
                    >
                      <div className="flex items-center">
                        <EnvelopeIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} mr-3`} />
                        <div>
                          <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                            {blocked.blocked_email}
                          </p>
                          <p className={`text-xs ${getThemeClasses("text-secondary")}`}>
                            Blocked on{" "}
                            {new Date(blocked.created_at).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                      <Button
                        onClick={() => handleRemoveEmail(blocked.blocked_email)}
                        variant="danger"
                        size="sm"
                        disabled={deleteLoading === blocked.blocked_email}
                        loading={deleteLoading === blocked.blocked_email}
                      >
                        {deleteLoading !== blocked.blocked_email && (
                          <span className="inline-flex items-center gap-1">
                            <TrashIcon className="h-4 w-4" />
                            <span>Unblock</span>
                          </span>
                        )}
                        {deleteLoading === blocked.blocked_email && "Removing..."}
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </Card>

            {/* Info section */}
            <Alert type="info" className="mt-6">
              <div>
                <h3 className={`text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}>
                  How blocking works
                </h3>
                <ul className={`text-sm ${getThemeClasses("text-secondary")} space-y-1`}>
                  <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>
            </Alert>
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(BlockedUsers);
