// File: src/pages/User/Me/DeleteAccount.jsx
import React, { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuth } from "../../../services/Services";
import withPasswordProtection from "../../../hocs/withPasswordProtection";
import Layout from "../../../components/Layout/Layout";
import {
  Button,
  Input,
  Alert,
  Card,
  Breadcrumb,
  Spinner,
  useUIXTheme,
} from "../../../components/UIX";
import {
  ExclamationTriangleIcon,
  ShieldExclamationIcon,
  TrashIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  XCircleIcon,
  InformationCircleIcon,
  LockClosedIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

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

  // State management
  const [currentStep, setCurrentStep] = useState(1);
  const [password, setPassword] = useState("");
  const [confirmText, setConfirmText] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [userEmail, setUserEmail] = useState("");
  const [acknowledgments, setAcknowledgments] = useState({
    permanentDeletion: false,
    dataLoss: false,
    gdprRights: false,
  });

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

  // Load user info
  useEffect(() => {
    const loadUserInfo = async () => {
      try {
        const user = await meManager.getCurrentUser();
        if (!isMountedRef.current) return;
        setUserEmail(user.email);
      } catch (err) {
        if (!isMountedRef.current) return;
        if (import.meta.env.DEV) {
          console.error("Failed to load user info:", err);
        }
        setError("Failed to load your account information.");
      }
    };
    loadUserInfo();
  }, [meManager]);

  // Check if all acknowledgments are checked
  const allAcknowledged =
    acknowledgments.permanentDeletion &&
    acknowledgments.dataLoss &&
    acknowledgments.gdprRights;

  // Check if confirmation text matches
  const confirmationMatches = confirmText === "DELETE MY ACCOUNT";

  // Handle checkbox change
  const handleAcknowledgmentChange = (key) => {
    setAcknowledgments((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  // Handle back button
  const handleBack = useCallback(() => {
    if (currentStep === 1) {
      navigate("/me");
    } else {
      setCurrentStep(currentStep - 1);
      setError("");
    }
  }, [currentStep, navigate]);

  // Handle next step
  const handleNext = useCallback(() => {
    setError("");
    setCurrentStep(currentStep + 1);
  }, [currentStep]);

  // Handle account deletion
  const handleDeleteAccount = useCallback(async () => {
    if (!isMountedRef.current) return;

    if (!password) {
      setError("Please enter your password to confirm deletion.");
      return;
    }

    if (!allAcknowledged) {
      setError("Please acknowledge all statements before proceeding.");
      return;
    }

    if (!confirmationMatches) {
      setError('Please type "DELETE MY ACCOUNT" exactly to confirm.');
      return;
    }

    setLoading(true);
    setError("");

    try {
      // Call the delete API
      await meManager.deleteCurrentUser(password);

      if (!isMountedRef.current) return;

      // Show success message and logout
      setCurrentStep(4); // Success step

      // Wait 3 seconds then logout and redirect
      setTimeout(() => {
        if (!isMountedRef.current) return;
        authManager.logout();
        navigate("/");
      }, 3000);
    } catch (err) {
      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.error("Account deletion failed:", err);
      }

      // Handle specific error cases
      if (err.response?.status === 401) {
        setError("Invalid password. Please try again.");
      } else if (err.response?.status === 403) {
        setError("You do not have permission to delete this account.");
      } else if (err.response?.data?.message) {
        setError(err.response.data.message);
      } else {
        setError("Failed to delete account. Please try again or contact support.");
      }
    } finally {
      if (isMountedRef.current) {
        setLoading(false);
      }
    }
  }, [password, allAcknowledged, confirmationMatches, meManager, authManager, navigate]);

  // Render Step 1: Warning and Information
  const renderStep1 = () => (
    <div className="space-y-6">
      {/* Warning Banner */}
      <Alert type="error">
        <div className="flex items-start">
          <ExclamationTriangleIcon className={`h-6 w-6 ${getThemeClasses("text-error")} mr-3 flex-shrink-0 mt-0.5`} />
          <div>
            <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
              This action is permanent and cannot be undone
            </h3>
            <p className={getThemeClasses("text-secondary")}>
              Once you delete your account, all your data will be permanently
              removed from our servers. This includes all files, collections,
              and personal information.
            </p>
          </div>
        </div>
      </Alert>

      {/* What will be deleted */}
      <Card className={`border ${getThemeClasses("border-muted")} p-6`}>
        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center`}>
          <TrashIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
          What will be deleted
        </h3>
        <ul className="space-y-3">
          <li className="flex items-start">
            <XCircleIcon className={`h-5 w-5 ${getThemeClasses("text-error")} mr-3 flex-shrink-0 mt-0.5`} />
            <div>
              <strong className={getThemeClasses("text-primary")}>All your files</strong>
              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                Every file you've uploaded will be permanently deleted from our
                servers
              </p>
            </div>
          </li>
          <li className="flex items-start">
            <XCircleIcon className={`h-5 w-5 ${getThemeClasses("text-error")} mr-3 flex-shrink-0 mt-0.5`} />
            <div>
              <strong className={getThemeClasses("text-primary")}>All your collections</strong>
              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                All folders and collections you own will be permanently removed
              </p>
            </div>
          </li>
          <li className="flex items-start">
            <XCircleIcon className={`h-5 w-5 ${getThemeClasses("text-error")} mr-3 flex-shrink-0 mt-0.5`} />
            <div>
              <strong className={getThemeClasses("text-primary")}>Personal information</strong>
              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                Your profile, email, and all associated data will be deleted
              </p>
            </div>
          </li>
          <li className="flex items-start">
            <XCircleIcon className={`h-5 w-5 ${getThemeClasses("text-error")} mr-3 flex-shrink-0 mt-0.5`} />
            <div>
              <strong className={getThemeClasses("text-primary")}>Shared access</strong>
              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                You'll be removed from any collections shared with you
              </p>
            </div>
          </li>
          <li className="flex items-start">
            <XCircleIcon className={`h-5 w-5 ${getThemeClasses("text-error")} mr-3 flex-shrink-0 mt-0.5`} />
            <div>
              <strong className={getThemeClasses("text-primary")}>Storage usage history</strong>
              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                All your storage metrics and usage history will be deleted
              </p>
            </div>
          </li>
        </ul>
      </Card>

      {/* GDPR Information */}
      <Alert type="info">
        <div className="flex items-start">
          <InformationCircleIcon className={`h-5 w-5 ${getThemeClasses("text-info")} mr-3 flex-shrink-0 mt-0.5`} />
          <div>
            <h4 className={`text-sm font-semibold ${getThemeClasses("text-primary")} mb-1`}>
              Your Right to Erasure (GDPR Article 17)
            </h4>
            <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
              This deletion process complies with GDPR regulations. All your
              personal data will be permanently erased from our systems within
              moments of confirmation. This action cannot be reversed.
            </p>
          </div>
        </div>
      </Alert>

      {/* Action Buttons */}
      <div className="flex justify-between pt-4">
        <Button onClick={handleBack} variant="secondary">
          <span className="inline-flex items-center gap-2">
            <ArrowLeftIcon className="h-4 w-4" />
            <span>Cancel</span>
          </span>
        </Button>
        <Button onClick={handleNext} variant="danger">
          Continue to Confirmation
        </Button>
      </div>
    </div>
  );

  // Render Step 2: Acknowledgments
  const renderStep2 = () => (
    <div className="space-y-6">
      <Alert type="warning">
        <div className="flex items-start">
          <ShieldExclamationIcon className={`h-6 w-6 ${getThemeClasses("text-warning")} mr-3 flex-shrink-0 mt-0.5`} />
          <div>
            <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
              Please confirm you understand
            </h3>
            <p className={getThemeClasses("text-secondary")}>
              Before proceeding, you must acknowledge the following statements
              about your account deletion.
            </p>
          </div>
        </div>
      </Alert>

      {/* Acknowledgment Checkboxes */}
      <Card className={`border ${getThemeClasses("border-muted")} p-6 space-y-4`}>
        <div className="flex items-start">
          <input
            type="checkbox"
            id="ack-permanent"
            checked={acknowledgments.permanentDeletion}
            onChange={() => handleAcknowledgmentChange("permanentDeletion")}
            className={`mt-1 h-4 w-4 ${getThemeClasses("text-accent")} focus:ring-2 ${getThemeClasses("border-muted")} rounded`}
          />
          <label
            htmlFor="ack-permanent"
            className={`ml-3 text-sm ${getThemeClasses("text-secondary")} cursor-pointer`}
          >
            <strong className={getThemeClasses("text-primary")}>
              I understand that this deletion is permanent and irreversible.
            </strong>{" "}
            Once deleted, my account and all associated data cannot be
            recovered.
          </label>
        </div>

        <div className="flex items-start">
          <input
            type="checkbox"
            id="ack-data"
            checked={acknowledgments.dataLoss}
            onChange={() => handleAcknowledgmentChange("dataLoss")}
            className={`mt-1 h-4 w-4 ${getThemeClasses("text-accent")} focus:ring-2 ${getThemeClasses("border-muted")} rounded`}
          />
          <label
            htmlFor="ack-data"
            className={`ml-3 text-sm ${getThemeClasses("text-secondary")} cursor-pointer`}
          >
            <strong className={getThemeClasses("text-primary")}>
              I understand that all my files and collections will be permanently
              deleted.
            </strong>{" "}
            I have downloaded or backed up any important data I wish to keep.
          </label>
        </div>

        <div className="flex items-start">
          <input
            type="checkbox"
            id="ack-gdpr"
            checked={acknowledgments.gdprRights}
            onChange={() => handleAcknowledgmentChange("gdprRights")}
            className={`mt-1 h-4 w-4 ${getThemeClasses("text-accent")} focus:ring-2 ${getThemeClasses("border-muted")} rounded`}
          />
          <label
            htmlFor="ack-gdpr"
            className={`ml-3 text-sm ${getThemeClasses("text-secondary")} cursor-pointer`}
          >
            <strong className={getThemeClasses("text-primary")}>
              I am exercising my right to erasure under GDPR Article 17.
            </strong>{" "}
            I understand that this will result in the immediate and complete
            deletion of all my personal data from MapleFile servers.
          </label>
        </div>
      </Card>

      {/* Current Account */}
      <div className={`${getThemeClasses("bg-muted")} border ${getThemeClasses("border-muted")} rounded-lg p-4`}>
        <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
          Account to be deleted:{" "}
          <strong className={getThemeClasses("text-primary")}>{userEmail}</strong>
        </p>
      </div>

      {/* Action Buttons */}
      <div className="flex justify-between pt-4">
        <Button onClick={handleBack} variant="secondary">
          <span className="inline-flex items-center gap-2">
            <ArrowLeftIcon className="h-4 w-4" />
            <span>Back</span>
          </span>
        </Button>
        <Button
          onClick={handleNext}
          disabled={!allAcknowledged}
          variant="danger"
        >
          Continue to Final Step
        </Button>
      </div>
    </div>
  );

  // Render Step 3: Final Confirmation
  const renderStep3 = () => (
    <div className="space-y-6">
      <Alert type="error">
        <div className="flex items-start">
          <ExclamationTriangleIcon className={`h-8 w-8 ${getThemeClasses("text-error")} mr-3 flex-shrink-0`} />
          <div>
            <h3 className={`text-xl font-bold ${getThemeClasses("text-primary")} mb-2`}>
              Final Confirmation Required
            </h3>
            <p className={getThemeClasses("text-secondary")}>
              This is your last chance to cancel. After clicking "Delete My
              Account", your data will be permanently erased.
            </p>
          </div>
        </div>
      </Alert>

      {/* Password Confirmation */}
      <Card className={`border ${getThemeClasses("border-muted")} p-6 space-y-4`}>
        <Input
          label="Enter your password to confirm"
          type="password"
          name="password"
          value={password}
          onChange={(value) => {
            setPassword(value);
            setError("");
          }}
          placeholder="Your account password"
          disabled={loading}
          icon={LockClosedIcon}
        />

        <div>
          <label
            htmlFor="confirm-text"
            className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}
          >
            Type <strong>"DELETE MY ACCOUNT"</strong> to confirm (exactly as
            shown)
          </label>
          <Input
            type="text"
            name="confirm-text"
            value={confirmText}
            onChange={(value) => {
              setConfirmText(value);
              setError("");
            }}
            placeholder="DELETE MY ACCOUNT"
            disabled={loading}
            error={confirmText && !confirmationMatches ? 'Text must match exactly: "DELETE MY ACCOUNT"' : ""}
          />
        </div>
      </Card>

      {/* Error Display */}
      {error && (
        <Alert type="error" onClose={() => setError("")}>
          {error}
        </Alert>
      )}

      {/* Action Buttons */}
      <div className="flex justify-between pt-4">
        <Button onClick={handleBack} variant="secondary" disabled={loading}>
          <span className="inline-flex items-center gap-2">
            <ArrowLeftIcon className="h-4 w-4" />
            <span>Back</span>
          </span>
        </Button>
        <Button
          onClick={handleDeleteAccount}
          disabled={loading || !password || !confirmationMatches || !allAcknowledged}
          variant="danger"
          loading={loading}
        >
          {!loading && (
            <span className="inline-flex items-center gap-2">
              <TrashIcon className="h-4 w-4" />
              <span>Delete My Account</span>
            </span>
          )}
          {loading && "Deleting Account..."}
        </Button>
      </div>
    </div>
  );

  // Render Step 4: Success
  const renderStep4 = () => (
    <div className="space-y-6">
      <div className={`${getThemeClasses("bg-success-light")} border-2 ${getThemeClasses("border-success")} p-8 rounded-lg text-center`}>
        <CheckCircleIcon className={`h-16 w-16 ${getThemeClasses("text-success")} mx-auto mb-4`} />
        <h3 className={`text-2xl font-bold ${getThemeClasses("text-primary")} mb-2`}>
          Account Deleted Successfully
        </h3>
        <p className={`${getThemeClasses("text-secondary")} mb-4`}>
          Your account and all associated data have been permanently deleted
          from our servers.
        </p>
        <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
          You will be logged out and redirected to the home page in a few
          seconds...
        </p>
      </div>

      <Alert type="info">
        <div className="flex items-start">
          <InformationCircleIcon className={`h-5 w-5 ${getThemeClasses("text-info")} mr-3 flex-shrink-0 mt-0.5`} />
          <div>
            <strong className={getThemeClasses("text-primary")}>Thank you for using MapleFile.</strong>
            <p className={`mt-1 ${getThemeClasses("text-secondary")}`}>
              If you have any feedback or concerns, please contact our support
              team. You're always welcome to create a new account in the future.
            </p>
          </div>
        </div>
      </Alert>
    </div>
  );

  // Progress indicator
  const renderProgressIndicator = () => {
    if (currentStep === 4) return null; // Hide on success page

    const steps = [
      { number: 1, label: "Warning" },
      { number: 2, label: "Acknowledgment" },
      { number: 3, label: "Confirmation" },
    ];

    return (
      <div className="mb-8">
        {/* Progress Steps */}
        <div className="flex items-center">
          {steps.map((step, index) => (
            <React.Fragment key={step.number}>
              {/* Step Circle */}
              <div className="flex flex-col items-center">
                <div
                  className={`flex items-center justify-center w-10 h-10 rounded-full border-2 transition-colors ${
                    currentStep >= step.number
                      ? `${getThemeClasses("border-error")} ${getThemeClasses("bg-error")} text-white`
                      : `${getThemeClasses("border-muted")} ${getThemeClasses("bg-card")} ${getThemeClasses("text-secondary")}`
                  }`}
                >
                  {currentStep > step.number ? (
                    <CheckCircleIcon className="h-6 w-6" />
                  ) : (
                    <span className="font-semibold">{step.number}</span>
                  )}
                </div>
                {/* Step Label */}
                <span
                  className={`mt-2 text-xs whitespace-nowrap ${
                    currentStep >= step.number
                      ? `font-semibold ${getThemeClasses("text-error")}`
                      : getThemeClasses("text-secondary")
                  }`}
                >
                  {step.label}
                </span>
              </div>

              {/* Connector Line */}
              {index < steps.length - 1 && (
                <div
                  className={`flex-1 h-1 mx-4 mb-6 transition-colors ${
                    currentStep > step.number ? getThemeClasses("bg-error") : getThemeClasses("bg-muted")
                  }`}
                />
              )}
            </React.Fragment>
          ))}
        </div>
      </div>
    );
  };

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

  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 ${getThemeClasses("bg-error")}`}>
                    <TrashIcon 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`}>
                      Delete Account
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Permanently delete your MapleFile account and all associated data
                    </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>

          {/* Content */}
          <div className="p-6">
            {/* Progress Indicator */}
            {renderProgressIndicator()}

            {/* Step Content */}
            {currentStep === 1 && renderStep1()}
            {currentStep === 2 && renderStep2()}
            {currentStep === 3 && renderStep3()}
            {currentStep === 4 && renderStep4()}
          </div>
        </Card>

        {/* Footer Notice */}
        {currentStep !== 4 && (
          <div className={`mt-6 text-center text-sm ${getThemeClasses("text-secondary")}`}>
            <p>
              Need help? Contact our support team at{" "}
              <a
                href="mailto:support@maplefile.com"
                className={getThemeClasses("link-primary")}
              >
                support@maplefile.com
              </a>
            </p>
          </div>
        )}
      </div>
    </Layout>
  );
};

export default withPasswordProtection(DeleteAccount);
