// ✅ DeleteAccountPage (FULL FILE) - Toast only (NO inline serverError box)
// - Requires: checkbox agree + typing DELETE/حذف
// - Calls: DELETE /api/user/web/{id}
// - Then logs out (server logoutApi) with fallback to local logout
"use client";

import React, { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { Formik } from "formik";
import toast from "react-hot-toast";

import ArrowBackIosNewRoundedIcon from "@mui/icons-material/ArrowBackIosNewRounded";
import PersonOutlineIcon from "@mui/icons-material/PersonOutline";

import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import LoadingSpinner from "@/components/ui/LoadingSpinner";
import api from "@/lib/axios";
import { useAuth } from "@/context/AuthContext";

const getApiErrorMessage = (err, fallback = "Something went wrong") => {
  const status = err?.response?.status;
  const data = err?.response?.data;

  const errorsObj = data?.errors;
  if (errorsObj && typeof errorsObj === "object") {
    const firstKey = Object.keys(errorsObj)[0];
    const firstMsg = Array.isArray(errorsObj[firstKey])
      ? errorsObj[firstKey][0]
      : String(errorsObj[firstKey] ?? "");
    if (firstMsg) return firstMsg;
  }

  if (typeof data?.message === "string" && data.message.trim()) return data.message;

  if (!err?.response) return "Network error. Please check your connection.";
  if (status === 401) return "Session expired. Please login again.";
  if (status === 403) return "Access denied.";
  if (status === 404) return "Service not found.";
  if (status >= 500) return "Server error. Please try again later.";

  return fallback;
};

export default function DeleteAccountPage() {
  const { t, i18n } = useTranslation();
  const router = useRouter();

  const { user, authReady, logoutApi, logout } = useAuth();

  const [agree, setAgree] = useState(false);
  const [confirmText, setConfirmText] = useState("");
  const [reason, setReason] = useState("");
  const [feedback, setFeedback] = useState("");
  const [fieldErrors, setFieldErrors] = useState({}); // ✅ for email mismatch edge cases

  const isArabic = (i18n?.language || "").toLowerCase().startsWith("ar");

  useEffect(() => {
    setFieldErrors({});
  }, [agree, confirmText, reason, feedback]);

  const canSubmit = useMemo(() => {
    if (!agree) return false;
    const cleaned = confirmText.trim();
    if (!cleaned) return false;

    if (cleaned.toUpperCase() === "DELETE") return true;
    if (isArabic && cleaned === "حذف") return true;

    return false;
  }, [agree, confirmText, isArabic]);

  if (!authReady) {
    return (
      <div className="custom-container py-10">
        <div className="h-[500px] w-full rounded-2xl bg-gray-100 animate-pulse" />
      </div>
    );
  }

  if (!user) {
    return (
      <div className="custom-container py-10">
        <div className="flex flex-col items-center justify-center h-[70vh]">
          <div className="w-24 h-24 mb-6 bg-[#F5F4F2] rounded-full flex items-center justify-center">
            <PersonOutlineIcon className="text-gray-400" sx={{ fontSize: 48 }} />
          </div>
          <h2 className="text-2xl font-bold text-gray-700 mb-2">
            {t("profile.not_signed_in_title", "You're not signed in")}
          </h2>
          <p className="text-gray-500 mb-6 text-center max-w-md">
            {t(
              "profile.not_signed_in_desc",
              "Please Login / Sign Up to access your profile and account settings."
            )}
          </p>
          <Button
            onClick={() => router.push("/auth/login")}
            variant="primary"
            size="lg"
            className="rounded-full md:px-7 py-3 text-base"
          >
            {t("profile.login_signup", "Login / Sign Up")}
          </Button>
        </div>
      </div>
    );
  }

  const userEmail = (user?.email || "").trim().toLowerCase();

  return (
    <div className="py-10 custom-container mx-auto px-2 sm:px-4">
      <div className="flex items-center gap-3 mb-5">
        <button
          onClick={() => router.back()}
          className="w-9 h-9 p-2 flex items-center justify-center bg-[#F5F4F2] rounded-full hover:shadow"
          aria-label={t("nav.back", "Back")}
        >
          <ArrowBackIosNewRoundedIcon className="rtl-flip" sx={{ fontSize: 18 }} />
        </button>

        <h1 className="font-normal text-[17px] sm:text-[21px] text-[#222222]">
          {t("profile.delete_account", "Delete Account")}
        </h1>
      </div>

      <div className="max-w-2xl mx-auto mb-4 bg-[#FFF0E6] border border-orange-200 text-orange-800 rounded-lg p-4">
        {t(
          "profile.delete_warning",
          "⚠️ Before deletion: If you have any pending orders or outstanding invoices, please make sure to complete them or download a copy."
        )}
      </div>

      <Formik
        enableReinitialize
        initialValues={{ email: user?.email || "" }}
        validate={(values) => {
          const errors = {};

          if (!values.email?.trim())
            errors.email = t("auth.register.errors.email_required");
          else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
            errors.email = t("auth.register.errors.email_invalid");
          }

          const inputEmail = (values.email || "").trim().toLowerCase();
          if (inputEmail && userEmail && inputEmail !== userEmail) {
            errors.email =
              t("profile.delete_email_must_match", "Email must match your account email") ||
              "Email must match your account email";
          }

          return errors;
        }}
        onSubmit={async (values, { setSubmitting, setFieldError }) => {
          // ✅ hard guard + toast
          if (!canSubmit) {
            toast.error(
              t(
                "profile.delete_confirm_required",
                isArabic
                  ? "يرجى الموافقة ثم كتابة DELETE (أو حذف) للتأكيد"
                  : "Please accept the agreement and type DELETE (or حذف) to confirm"
              )
            );
            return;
          }

          setFieldErrors({});

          const inputEmail = (values.email || "").trim().toLowerCase();
          if (userEmail && inputEmail !== userEmail) {
            const msg = t(
              "profile.delete_email_must_match",
              "Email must match your account email"
            );
            setFieldError("email", msg);
            setFieldErrors({ email: msg });
            toast.error(msg);
            setSubmitting(false);
            return;
          }

          const toastId = toast.loading(
            t("profile.deleting", "Deleting your account...")
          );

          try {
            if (!user?.id) throw new Error("User ID missing");

            await api.delete(`/api/user/web/${user.id}`, {
              data: {
                email: user.email,
                reason: reason || undefined,
                feedback: feedback || undefined,
              },
            });

            toast.success(
              t("profile.delete_success", "Account deleted successfully"),
              { id: toastId }
            );

            // logout
            try {
              await logoutApi?.();
            } catch {
              logout?.();
            }

            if (typeof window !== "undefined") window.location.replace("/");
            else router.push("/");
          } catch (err) {
            toast.error(
              getApiErrorMessage(
                err,
                t("profile.delete_failed", "Failed to delete account. Please try again later.")
              ),
              { id: toastId }
            );
          } finally {
            setSubmitting(false);
          }
        }}
      >
        {({ values, handleBlur, handleSubmit, touched, errors, isValid, isSubmitting }) => (
          <form
            onSubmit={handleSubmit}
            className="max-w-2xl mx-auto bg-white rounded-xl p-5 space-y-5 shadow-sm"
          >
            <div className="space-y-2">
              <h2 className="text-[20px] sm:text-[24px] font-semibold text-[#222]">
                {t("profile.delete_title", "Permanently Delete Account")}
              </h2>
              <p className="text-sm text-gray-600 leading-6">
                {t(
                  "profile.delete_desc",
                  "This is an irreversible action. Your profile data will be deleted and your access disabled. Some records may be retained for legal or accounting purposes according to our policy."
                )}
              </p>
            </div>

            <div className="grid gap-4">
              <Input
                required
                name="email"
                type="email"
                label={t("profile.email_address", "Email Address")}
                value={values.email}
                readOnly
                disabled
                onBlur={handleBlur}
                startIcon={PersonOutlineIcon}
                error={(touched.email && errors.email) || fieldErrors.email || ""}
              />

              <Input
                name="reason"
                label={t("profile.delete_reason", "Reason for deletion (optional)")}
                placeholder={t("profile.delete_reason_ph", "Enter your reason")}
                value={reason}
                onChange={(e) => setReason(e.target.value)}
              />

              <Input
                name="feedback"
                label={t("profile.delete_feedback", "Feedback / Suggestions (optional)")}
                placeholder={t("profile.delete_feedback_ph", "Help us improve")}
                value={feedback}
                onChange={(e) => setFeedback(e.target.value)}
              />
            </div>

            <div className="bg-[#FFF5F5] border border-red-200 rounded-lg p-4 space-y-3">
              <label className="flex items-start gap-3 text-sm text-gray-700">
                <input
                  type="checkbox"
                  className="mt-1"
                  checked={agree}
                  onChange={(e) => setAgree(e.target.checked)}
                />
                <span>
                  {t(
                    "profile.delete_agree",
                    "I agree to delete my account and all associated data (understanding that the system may retain limited backups or legal records as per the policy)."
                  )}
                </span>
              </label>

              <div>
                <p className="text-sm text-gray-700 mb-2">
                  {t("profile.type_delete", "Type DELETE to confirm:")}
                </p>
                <Input
                  name="confirm"
                  placeholder={t("profile.type_delete_ph", "Type DELETE here")}
                  value={confirmText}
                  onChange={(e) => setConfirmText(e.target.value)}
                  dir={isArabic ? "rtl" : "ltr"}
                />
              </div>
            </div>

            <div className="flex max-sm:flex-col-reverse sm:flex-row gap-3 sm:items-center sm:justify-between">
              <Button
                type="button"
                variant="outline"
                size="md"
                className="h-10"
                onClick={() => router.back()}
              >
                {t("nav.cancel")}
              </Button>

              <Button
                type="submit"
                className="text-white h-10 min-w-[260px]"
                disabled={!(canSubmit && values.email && isValid) || isSubmitting}
                size="md"
                variant="primary"
              >
                {isSubmitting ? (
                  <div className="flex items-center gap-2">
                    <LoadingSpinner size="w-5 h-5" color="white" />
                  </div>
                ) : (
                  t("profile.delete_submit", "Permanently Delete Account")
                )}
              </Button>
            </div>
          </form>
        )}
      </Formik>
    </div>
  );
}
