"use client";
import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { useRouter } from "next/navigation";
import { AlertTriangle, ArrowLeft, ShieldAlert, Trash2 } from "lucide-react";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import apis from "@/utils/apis";
import { Modal } from "@/components/ui/modal";
import { useGlobalContext } from "@/context/Provider";
import { useDispatch } from "react-redux";
import { cartReset, updateAddress } from "@/store/actions/user/userAction";
import { AppDispatch } from "@/store/store";

const DeleteAccount = () => {
  const { Toast, setUserInfo } = useGlobalContext();
  const dispatch = useDispatch<AppDispatch>();
  const [formData, setFormData] = useState({
    message: "",
  });
  const [reason, setReason] = useState("");
  const [isOpen1, setIsOpen1] = useState(false);
  const [reasonList, setReasonList] = useState<any[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const router = useRouter();

  useEffect(() => {
    const fetchReasons = async () => {
      try {
        const res = await apis.Auth.getReport("type=account_delete&page=1&limit=10");
        setReasonList(res?.data || []);
      } catch (error) {
        Toast.error(error);
      }
    };

    fetchReasons();
  }, []);

  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: any) => {
    e.preventDefault();
    let payload = {
      report_reason_id: reason,
      delete_description: formData?.message,
    };
    try {
      setIsSubmitting(true);
      const apiRes = await apis.Auth.deleteAccount(payload);
      if (apiRes) {
        setIsOpen1(false);

        // Clear global state
        setUserInfo && setUserInfo(null);
        dispatch(cartReset());
        dispatch(updateAddress(null));

        // Clear everything
        sessionStorage.clear();
        localStorage.clear();

        // Clear all cookies
        const cookies = document.cookie.split(";");
        for (let i = 0; i < cookies.length; i++) {
          const cookie = cookies[i];
          const eqPos = cookie.indexOf("=");
          const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
          document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
        }

        router.push("/home");
      }
    } catch (error: any) {
      Toast.error(error);
    } finally {
      setIsSubmitting(false);
    }
    setFormData({ message: "" });
  };

  const handleModalOpen = (e: any) => {
    e.preventDefault();
    if (!reason) {
      Toast.error("Select reason first!");
      return;
    }
    if (!formData?.message) {
      Toast.error("Enter message first!");
      return;
    }
    setIsOpen1(true);
  };

  return (
    <div className="w-full max-w-2xl mx-auto py-8 px-4 sm:px-6">
      {/* Back Button */}
      <button
        onClick={() => router.push("/profile")}
        className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-800 mb-6 transition-colors group"
      >
        <ArrowLeft className="w-4 h-4 mr-1.5 transition-transform group-hover:-translate-x-1" />
        Back to Profile
      </button>

      {/* Main Card */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 sm:p-8 space-y-6">
        {/* Card Header */}
        <div className="flex items-center gap-4 border-b border-gray-100 pb-6">
          <div className="w-12 h-12 rounded-2xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary shrink-0">
            <ShieldAlert className="w-6 h-6" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Delete Account</h1>
            <p className="text-sm text-gray-500 mt-0.5">
              We're sorry to see you go. Please let us know why you are leaving.
            </p>
          </div>
        </div>

        {/* Warning Banner */}
        <div className="bg-primary/5 border border-primary/20 rounded-xl p-4 flex gap-3 text-gray-800 text-sm">
          <AlertTriangle className="w-5 h-5 text-primary shrink-0 mt-0.5" />
          <div>
            <p className="font-semibold text-gray-900">This action cannot be undone</p>
            <p className="text-gray-600 text-xs mt-1 leading-relaxed">
              Permanently deleting your account will erase your profile information, order history, saved addresses, and active rewards.
            </p>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleModalOpen} className="space-y-5">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Reason for deletion <span className="text-red-500">*</span>
            </label>
            <Select onValueChange={(val: any) => setReason(val)} value={reason}>
              <SelectTrigger className="w-full px-4 py-3 h-12 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary text-gray-800 bg-white text-sm">
                <SelectValue placeholder="Select reason" />
              </SelectTrigger>
              <SelectContent>
                <SelectGroup>
                  {reasonList.map((item: any) => (
                    <SelectItem key={item._id} value={item._id} className="py-2.5 text-sm cursor-pointer">
                      {item.reason}
                    </SelectItem>
                  ))}
                </SelectGroup>
              </SelectContent>
            </Select>
          </div>

          <div>
            <div className="flex justify-between items-center mb-2">
              <label className="block text-sm font-medium text-gray-700">
                Additional feedback <span className="text-red-500">*</span>
              </label>
              <span className="text-xs text-gray-400 font-medium">
                {formData.message.length} / 220
              </span>
            </div>
            <textarea
              name="message"
              value={formData.message}
              onChange={handleChange}
              placeholder="Please explain us in brief..."
              rows={5}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary text-gray-800 text-sm placeholder:text-gray-400 transition-all resize-none"
              required
              maxLength={220}
            />
          </div>

          <div className="pt-2 flex flex-col-reverse sm:flex-row items-center gap-3">
            <button
              type="button"
              onClick={() => router.push("/profile")}
              className="w-full sm:w-1/2 py-3 px-4 border border-gray-200 hover:bg-gray-50 text-gray-700 font-medium rounded-xl text-sm transition-colors text-center"
            >
              Keep My Account
            </button>
            <button
              type="submit"
              className="w-full sm:w-1/2 py-3 px-4 bg-primary hover:bg-primary/90 text-white font-semibold rounded-xl text-sm shadow-sm shadow-primary/20 transition-all flex items-center justify-center gap-2"
            >
              <Trash2 className="w-4 h-4" />
              Delete Account
            </button>
          </div>
        </form>
      </div>

      {/* Confirmation Modal */}
      <Modal
        isOpen={isOpen1}
        description=""
        onClose={() => !isSubmitting && setIsOpen1(false)}
        title="Confirm Account Deletion"
      >
        <div className="w-full pt-2 flex flex-col items-center text-center">
          <div className="w-12 h-12 rounded-full bg-primary/10 text-primary flex items-center justify-center mb-4">
            <AlertTriangle className="w-6 h-6" />
          </div>
          <p className="text-sm text-gray-600 mb-6 leading-relaxed">
            Are you sure you want to delete your account? All your order history, personal data, and preferences will be permanently removed.
          </p>
          <div className="flex flex-row gap-3 w-full">
            <button
              type="button"
              disabled={isSubmitting}
              onClick={() => setIsOpen1(false)}
              className="w-1/2 py-2.5 px-4 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-medium rounded-xl transition duration-200"
            >
              Cancel
            </button>
            <button
              type="button"
              disabled={isSubmitting}
              onClick={(e: any) => handleSubmit(e)}
              className="w-1/2 py-2.5 px-4 bg-primary hover:bg-primary/90 text-white text-sm font-semibold rounded-xl shadow-sm transition duration-200 flex items-center justify-center gap-2 disabled:opacity-50"
            >
              {isSubmitting ? "Deleting..." : "Yes, Delete"}
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <DeleteAccount />
    </DashboardLayout>
  );
}

