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

function DeleteAccount() {
  const navigate = useNavigate();

  // 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,
  });

  // Load user info
  useEffect(() => {
    let attempts = 0;
    const maxAttempts = 50;
    let isCancelled = false;

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

      if (window.go && window.go.app && window.go.app.Application) {
        loadUserInfo();
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkWailsReady, 100);
      }
    };

    checkWailsReady();

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

  const loadUserInfo = async () => {
    try {
      const user = await GetUserProfile();
      setUserEmail(user.email);
    } catch (err) {
      console.error("Failed to load user info:", err);
      setError("Failed to load your account information.");
    }
  };

  // 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 = () => {
    if (currentStep === 1) {
      navigate("/me");
    } else {
      setCurrentStep(currentStep - 1);
      setError("");
    }
  };

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

  // Handle account deletion
  const handleDeleteAccount = async () => {
    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 {
      await DeleteAccountAPI(password);
      setCurrentStep(4); // Success step

      // Wait 3 seconds then redirect to login
      setTimeout(() => {
        navigate("/login");
      }, 3000);
    } catch (err) {
      console.error("Account deletion failed:", err);
      const errorMessage = err.message || err.toString();

      if (errorMessage.includes("Invalid") || errorMessage.includes("password")) {
        setError("Invalid password. Please try again.");
      } else if (errorMessage.includes("permission")) {
        setError("You do not have permission to delete this account.");
      } else {
        setError("Failed to delete account. Please try again or contact support.");
      }
    } finally {
      setLoading(false);
    }
  };

  // Render Step 1: Warning and Information
  const renderStep1 = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
      {/* Warning Banner */}
      <div style={{
        background: "#fee2e2",
        borderLeft: "4px solid #ef4444",
        padding: "20px",
        borderRadius: "8px",
      }}>
        <div style={{ display: "flex", alignItems: "start" }}>
          <span style={{ fontSize: "24px", marginRight: "15px" }}>⚠️</span>
          <div>
            <h3 style={{ margin: "0 0 10px 0", color: "#991b1b", fontSize: "18px" }}>
              This action is permanent and cannot be undone
            </h3>
            <p style={{ margin: 0, color: "#7f1d1d" }}>
              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>
      </div>

      {/* What will be deleted */}
      <div style={{
        background: "white",
        padding: "25px",
        borderRadius: "12px",
        border: "1px solid #e5e7eb",
        boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
      }}>
        <h3 style={{ margin: "0 0 20px 0", color: "#2c3e50", fontSize: "18px", display: "flex", alignItems: "center" }}>
          <span style={{ marginRight: "10px" }}>🗑️</span>
          What will be deleted
        </h3>
        <div style={{ display: "flex", flexDirection: "column", gap: "15px" }}>
          {[
            { title: "All your files", desc: "Every file you've uploaded will be permanently deleted from our servers" },
            { title: "All your collections", desc: "All folders and collections you own will be permanently removed" },
            { title: "Personal information", desc: "Your profile, email, and all associated data will be deleted" },
            { title: "Shared access", desc: "You'll be removed from any collections shared with you" },
            { title: "Storage usage history", desc: "All your storage metrics and usage history will be deleted" }
          ].map((item, idx) => (
            <div key={idx} style={{ display: "flex", alignItems: "start" }}>
              <span style={{ fontSize: "20px", color: "#ef4444", marginRight: "12px" }}>✗</span>
              <div>
                <strong style={{ color: "#2c3e50" }}>{item.title}</strong>
                <p style={{ margin: "3px 0 0 0", fontSize: "14px", color: "#6b7280" }}>{item.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* GDPR Information */}
      <div style={{
        background: "#dbeafe",
        border: "1px solid #93c5fd",
        padding: "20px",
        borderRadius: "8px",
      }}>
        <div style={{ display: "flex", alignItems: "start" }}>
          <span style={{ fontSize: "20px", marginRight: "12px" }}>ℹ️</span>
          <div>
            <h4 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: "600", color: "#1e3a8a" }}>
              Your Right to Erasure (GDPR Article 17)
            </h4>
            <p style={{ margin: 0, fontSize: "14px", color: "#1e40af" }}>
              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>
      </div>

      {/* Action Buttons */}
      <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "15px" }}>
        <button onClick={handleBack} className="nav-button secondary">
          ← Cancel
        </button>
        <button onClick={handleNext} className="nav-button danger">
          Continue to Confirmation
        </button>
      </div>
    </div>
  );

  // Render Step 2: Acknowledgments
  const renderStep2 = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
      <div style={{
        background: "#fef3c7",
        borderLeft: "4px solid #f59e0b",
        padding: "20px",
        borderRadius: "8px",
      }}>
        <div style={{ display: "flex", alignItems: "start" }}>
          <span style={{ fontSize: "24px", marginRight: "15px" }}>🛡️</span>
          <div>
            <h3 style={{ margin: "0 0 10px 0", color: "#78350f", fontSize: "18px" }}>
              Please confirm you understand
            </h3>
            <p style={{ margin: 0, color: "#92400e" }}>
              Before proceeding, you must acknowledge the following statements about your account deletion.
            </p>
          </div>
        </div>
      </div>

      {/* Acknowledgment Checkboxes */}
      <div style={{
        background: "white",
        padding: "25px",
        borderRadius: "12px",
        border: "1px solid #e5e7eb",
        boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
        display: "flex",
        flexDirection: "column",
        gap: "20px",
      }}>
        <div style={{ display: "flex", alignItems: "start" }}>
          <input
            type="checkbox"
            id="ack-permanent"
            checked={acknowledgments.permanentDeletion}
            onChange={() => handleAcknowledgmentChange("permanentDeletion")}
            style={{ marginTop: "3px", marginRight: "12px", width: "18px", height: "18px" }}
          />
          <label htmlFor="ack-permanent" style={{ fontSize: "14px", color: "#374151", cursor: "pointer" }}>
            <strong style={{ color: "#2c3e50" }}>
              I understand that this deletion is permanent and irreversible.
            </strong>{" "}
            Once deleted, my account and all associated data cannot be recovered.
          </label>
        </div>

        <div style={{ display: "flex", alignItems: "start" }}>
          <input
            type="checkbox"
            id="ack-data"
            checked={acknowledgments.dataLoss}
            onChange={() => handleAcknowledgmentChange("dataLoss")}
            style={{ marginTop: "3px", marginRight: "12px", width: "18px", height: "18px" }}
          />
          <label htmlFor="ack-data" style={{ fontSize: "14px", color: "#374151", cursor: "pointer" }}>
            <strong style={{ color: "#2c3e50" }}>
              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 style={{ display: "flex", alignItems: "start" }}>
          <input
            type="checkbox"
            id="ack-gdpr"
            checked={acknowledgments.gdprRights}
            onChange={() => handleAcknowledgmentChange("gdprRights")}
            style={{ marginTop: "3px", marginRight: "12px", width: "18px", height: "18px" }}
          />
          <label htmlFor="ack-gdpr" style={{ fontSize: "14px", color: "#374151", cursor: "pointer" }}>
            <strong style={{ color: "#2c3e50" }}>
              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>
      </div>

      {/* Current Account */}
      <div style={{
        background: "#f9fafb",
        border: "1px solid #e5e7eb",
        padding: "15px",
        borderRadius: "8px",
      }}>
        <p style={{ margin: 0, fontSize: "14px", color: "#6b7280" }}>
          Account to be deleted:{" "}
          <strong style={{ color: "#2c3e50" }}>{userEmail}</strong>
        </p>
      </div>

      {/* Action Buttons */}
      <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "15px" }}>
        <button onClick={handleBack} className="nav-button secondary">
          ← Back
        </button>
        <button
          onClick={handleNext}
          disabled={!allAcknowledged}
          className="nav-button danger"
          style={{ opacity: allAcknowledged ? 1 : 0.5, cursor: allAcknowledged ? "pointer" : "not-allowed" }}
        >
          Continue to Final Step
        </button>
      </div>
    </div>
  );

  // Render Step 3: Final Confirmation
  const renderStep3 = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
      <div style={{
        background: "#fee2e2",
        border: "2px solid #ef4444",
        padding: "20px",
        borderRadius: "12px",
      }}>
        <div style={{ display: "flex", alignItems: "start" }}>
          <span style={{ fontSize: "32px", marginRight: "15px" }}>⚠️</span>
          <div>
            <h3 style={{ margin: "0 0 10px 0", color: "#7f1d1d", fontSize: "20px" }}>
              Final Confirmation Required
            </h3>
            <p style={{ margin: 0, color: "#991b1b" }}>
              This is your last chance to cancel. After clicking "Delete My Account", your data will be permanently erased.
            </p>
          </div>
        </div>
      </div>

      {/* Password Confirmation */}
      <div style={{
        background: "white",
        padding: "25px",
        borderRadius: "12px",
        border: "1px solid #e5e7eb",
        boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
        display: "flex",
        flexDirection: "column",
        gap: "20px",
      }}>
        <div>
          <label htmlFor="password" style={{ display: "block", fontSize: "14px", fontWeight: "500", color: "#374151", marginBottom: "8px" }}>
            <span style={{ marginRight: "8px" }}>🔒</span>
            Enter your password to confirm
          </label>
          <input
            type="password"
            id="password"
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
              setError("");
            }}
            style={{
              width: "100%",
              padding: "10px",
              border: "1px solid #d1d5db",
              borderRadius: "8px",
              fontSize: "14px",
            }}
            placeholder="Your account password"
            disabled={loading}
          />
        </div>

        <div>
          <label htmlFor="confirm-text" style={{ display: "block", fontSize: "14px", fontWeight: "500", color: "#374151", marginBottom: "8px" }}>
            Type <strong>"DELETE MY ACCOUNT"</strong> to confirm (exactly as shown)
          </label>
          <input
            type="text"
            id="confirm-text"
            value={confirmText}
            onChange={(e) => {
              setConfirmText(e.target.value);
              setError("");
            }}
            style={{
              width: "100%",
              padding: "10px",
              border: "1px solid #d1d5db",
              borderRadius: "8px",
              fontSize: "14px",
              fontFamily: "monospace",
            }}
            placeholder="DELETE MY ACCOUNT"
            disabled={loading}
          />
          {confirmText && !confirmationMatches && (
            <p style={{ margin: "5px 0 0 0", fontSize: "14px", color: "#dc2626" }}>
              Text must match exactly: "DELETE MY ACCOUNT"
            </p>
          )}
        </div>
      </div>

      {/* Error Display */}
      {error && (
        <div style={{
          background: "#fee2e2",
          border: "1px solid #fecaca",
          padding: "15px",
          borderRadius: "8px",
        }}>
          <div style={{ display: "flex", alignItems: "start" }}>
            <span style={{ fontSize: "20px", color: "#dc2626", marginRight: "12px" }}>✗</span>
            <p style={{ margin: 0, fontSize: "14px", color: "#991b1b" }}>{error}</p>
          </div>
        </div>
      )}

      {/* Action Buttons */}
      <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "15px" }}>
        <button
          onClick={handleBack}
          disabled={loading}
          className="nav-button secondary"
          style={{ opacity: loading ? 0.5 : 1 }}
        >
          ← Back
        </button>
        <button
          onClick={handleDeleteAccount}
          disabled={loading || !password || !confirmationMatches || !allAcknowledged}
          className="nav-button danger"
          style={{
            opacity: (loading || !password || !confirmationMatches || !allAcknowledged) ? 0.5 : 1,
            cursor: (loading || !password || !confirmationMatches || !allAcknowledged) ? "not-allowed" : "pointer",
          }}
        >
          {loading ? "🔄 Deleting Account..." : "🗑️ Delete My Account"}
        </button>
      </div>
    </div>
  );

  // Render Step 4: Success
  const renderStep4 = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
      <div style={{
        background: "#d1fae5",
        border: "2px solid #10b981",
        padding: "40px",
        borderRadius: "12px",
        textAlign: "center",
      }}>
        <span style={{ fontSize: "64px" }}>✓</span>
        <h3 style={{ margin: "15px 0 10px 0", color: "#065f46", fontSize: "24px" }}>
          Account Deleted Successfully
        </h3>
        <p style={{ margin: "0 0 15px 0", color: "#047857" }}>
          Your account and all associated data have been permanently deleted from our servers.
        </p>
        <p style={{ margin: 0, fontSize: "14px", color: "#059669" }}>
          You will be redirected to the login page in a few seconds...
        </p>
      </div>

      <div style={{
        background: "#dbeafe",
        border: "1px solid #93c5fd",
        padding: "20px",
        borderRadius: "8px",
      }}>
        <div style={{ display: "flex", alignItems: "start" }}>
          <span style={{ fontSize: "20px", marginRight: "12px" }}>ℹ️</span>
          <div style={{ fontSize: "14px", color: "#1e40af" }}>
            <strong style={{ color: "#1e3a8a" }}>Thank you for using MapleFile.</strong>
            <p style={{ margin: "8px 0 0 0" }}>
              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>
      </div>
    </div>
  );

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

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

    return (
      <div style={{ marginBottom: "30px" }}>
        <div style={{ display: "flex", alignItems: "center" }}>
          {steps.map((step, index) => (
            <div key={step.number} style={{ display: "flex", alignItems: "center", flex: index < steps.length - 1 ? 1 : "initial" }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                <div style={{
                  width: "40px",
                  height: "40px",
                  borderRadius: "50%",
                  border: `2px solid ${currentStep >= step.number ? "#dc2626" : "#d1d5db"}`,
                  background: currentStep >= step.number ? "#dc2626" : "white",
                  color: currentStep >= step.number ? "white" : "#9ca3af",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: "16px",
                  fontWeight: "600",
                }}>
                  {currentStep > step.number ? "✓" : step.number}
                </div>
                <span style={{
                  marginTop: "8px",
                  fontSize: "12px",
                  fontWeight: currentStep >= step.number ? "600" : "normal",
                  color: currentStep >= step.number ? "#dc2626" : "#6b7280",
                  whiteSpace: "nowrap",
                }}>
                  {step.label}
                </span>
              </div>
              {index < steps.length - 1 && (
                <div style={{
                  flex: 1,
                  height: "2px",
                  background: currentStep > step.number ? "#dc2626" : "#d1d5db",
                  marginBottom: "24px",
                  marginLeft: "15px",
                  marginRight: "15px",
                }} />
              )}
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Delete Account">
          <div style={{ maxWidth: "800px", margin: "0 auto" }}>
            {/* 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" }}>Delete Account</span>
            </div>

            {/* Header */}
            <div style={{ marginBottom: "30px" }}>
              <h1 style={{ margin: 0, color: "#2c3e50", fontSize: "28px", display: "flex", alignItems: "center" }}>
                <span style={{ fontSize: "32px", marginRight: "12px" }}>🗑️</span>
                Delete Account
              </h1>
              <p style={{ margin: "8px 0 0 0", color: "#6b7280" }}>
                Permanently delete your MapleFile account and all associated data
              </p>
            </div>

            {/* Progress Indicator */}
            {renderProgressIndicator()}

            {/* Main Content */}
            <div style={{
              background: "white",
              padding: "30px",
              borderRadius: "12px",
              boxShadow: "0 4px 6px rgba(0,0,0,0.1)",
            }}>
              {currentStep === 1 && renderStep1()}
              {currentStep === 2 && renderStep2()}
              {currentStep === 3 && renderStep3()}
              {currentStep === 4 && renderStep4()}
            </div>

            {/* Footer Notice */}
            {currentStep !== 4 && (
              <div style={{ marginTop: "20px", textAlign: "center", fontSize: "14px", color: "#6b7280" }}>
                <p style={{ margin: 0 }}>
                  Need help? Contact our support team at{" "}
                  <a href="mailto:support@maplefile.com" style={{ color: "#3b82f6", textDecoration: "none" }}>
                    support@maplefile.com
                  </a>
                </p>
              </div>
            )}
          </div>
        </Page>
      </div>
    </div>
  );
}

export default DeleteAccount;
