// File Path: monorepo/web/frontend/src/pages/Admin/Customer/Detail/More/Avatar/Delete/Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useParams } from "react-router";
import {
  TrashIcon,
  ExclamationTriangleIcon,
  ArrowLeftIcon,
  UserCircleIcon,
  PhotoIcon,
} from "@heroicons/react/24/outline";
import {
  useCustomerManager,
  useAuthManager,
} from "../../../../../../../services/Services";
import {
  Breadcrumb,
  PageHeader,
  FormCard,
  Alert,
  Button,
  Badge,
  Loading,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../../../components/UIX";
import { CUSTOMER_STATUS } from "../../../../../../../constants/Customer";

function AdminCustomerDetailMoreAvatarDeletePage() {
  // URL Parameters
  const { cid } = useParams();

  // Navigation
  const navigate = useNavigate();

  // Services
  const customerManager = useCustomerManager();
  const authManager = useAuthManager();

  // Theme
  const { getThemeClasses } = useUIXTheme();

  // Breadcrumb items
  const breadcrumbItems = useMemo(
    () => [
      { label: "Dashboard", to: "/admin/dashboard" },
      { label: "Customers", to: "/admin/customers" },
      { label: "Detail", to: `/admin/customer/${cid}` },
      { label: "More", to: `/admin/customer/${cid}/more` },
      { label: "Avatar", to: `/admin/customer/${cid}/more/avatar` },
      { label: "Delete Photo" },
    ],
    [cid],
  );

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(true);
  const [customer, setCustomer] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // Unauthorized callback
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Load customer details
  useEffect(() => {
    let mounted = true;

    const fetchCustomer = async () => {
      if (!authManager.isAuthenticated()) {
        navigate("/login");
        return;
      }

      setFetching(true);
      setErrors({});

      try {
        await customerManager.getCustomerDetailWithCallbacks(
          cid,
          (customerData) => {
            if (mounted) {
              setCustomer(customerData);
            }
          },
          (error) => {
            if (mounted) {
              if (import.meta.env.DEV) {
                console.error("Failed to fetch customer:", error);
              }
              setErrors(error);
            }
          },
          () => {
            if (mounted) {
              setFetching(false);
            }
          },
          onUnauthorized,
        );
      } catch (error) {
        if (mounted) {
          if (import.meta.env.DEV) {
            console.error("Failed to fetch customer:", error);
          }
          setErrors({ general: "Failed to load customer information" });
          setFetching(false);
        }
      }
    };

    if (cid) {
      fetchCustomer();
    } else {
      setErrors({ general: "Customer ID is required" });
      setFetching(false);
    }

    return () => {
      mounted = false;
    };
  }, [cid, customerManager, authManager, navigate, onUnauthorized]);

  // Handle delete avatar
  const handleDeleteAvatar = useCallback(async () => {
    setErrors({});
    setIsDeleting(true);

    try {
      await customerManager.deleteCustomerAvatarWithCallbacks(
        cid,
        () => {
          // Success - navigate back to more page
          navigate(`/admin/customer/${cid}/more`);
        },
        (error) => {
          // Error callback
          if (import.meta.env.DEV) {
            console.error("Failed to delete avatar:", error);
          }
          setErrors(error);
          setIsDeleting(false);
        },
        () => {
          // Done callback
          setIsDeleting(false);
        },
        onUnauthorized,
      );
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to delete avatar:", error);
      }
      setErrors({ general: "Failed to delete avatar" });
      setIsDeleting(false);
    }
  }, [cid, customerManager, navigate, onUnauthorized]);

  // Memoize customer name
  const customerName = useMemo(() => {
    if (!customer) return "";
    return `${customer.firstName} ${customer.lastName}`;
  }, [customer]);

  // Render loading state
  if (isFetching && !customer) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen bg-gray-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div className="flex items-center justify-center py-12">
              <Loading message="Loading customer details..." />
            </div>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  // If no avatar exists, show error
  if (customer && !customer.avatarObjectUrl) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen bg-gray-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            {breadcrumbItems && (
              <Breadcrumb items={breadcrumbItems} className="mb-6" />
            )}

            <Alert type="error" className="mb-6">
              <p className="font-semibold">No Photo to Delete</p>
              <p className="text-sm mt-1">
                This customer does not have a profile photo to delete.
              </p>
            </Alert>

            <Button
              variant="outline"
              onClick={() => navigate(`/admin/customer/${cid}/more`)}
              icon={ArrowLeftIcon}
            >
              Back to More
            </Button>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* Breadcrumb */}
          {breadcrumbItems && (
            <Breadcrumb items={breadcrumbItems} className="mb-6" />
          )}

          {/* Page Header */}
          <div className="mb-8">
            <PageHeader
              title="Delete Photo"
              subtitle={customerName}
              icon={TrashIcon}
            >
              <div className="flex items-center gap-2">
                {customer?.status === CUSTOMER_STATUS.ARCHIVED && (
                  <Badge variant="secondary">Archived</Badge>
                )}
                {customer?.isBanned && <Badge variant="error">Banned</Badge>}
              </div>
            </PageHeader>
          </div>

          {/* Error Messages */}
          {errors && Object.keys(errors).length > 0 && (
            <Alert
              type="error"
              message={
                errors.general ||
                errors.message ||
                errors.detail ||
                "An error occurred. Please try again."
              }
              className="mb-6"
              onDismiss={() => setErrors({})}
            />
          )}

          {/* Main Content Card */}
          <FormCard
            title="Confirm Photo Deletion"
            icon={ExclamationTriangleIcon}
            description="Permanent deletion confirmation"
            maxWidth="4xl"
          >
            {/* Warning Alert */}
            <Alert
              type="warning"
              icon={ExclamationTriangleIcon}
              className="mb-6"
            >
              <div className="space-y-2">
                <p className="font-semibold">
                  Warning: This Action Cannot Be Undone
                </p>
                <p className="text-sm">
                  You are about to permanently delete the profile photo for this
                  customer. This action is irreversible.
                </p>
              </div>
            </Alert>

            {/* Customer Information */}
            <div
              className={`${getThemeClasses("bg-disabled")} rounded-lg p-6 mb-6`}
            >
              <h3
                className={`text-sm font-semibold ${getThemeClasses("text-secondary")} mb-4 flex items-center`}
              >
                <UserCircleIcon className="w-5 h-5 mr-2" />
                Customer Information
              </h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span
                    className={`font-medium ${getThemeClasses("text-muted")}`}
                  >
                    Name:
                  </span>
                  <span className={getThemeClasses("text-primary")}>
                    {customerName}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span
                    className={`font-medium ${getThemeClasses("text-muted")}`}
                  >
                    Email:
                  </span>
                  <span className={getThemeClasses("text-primary")}>
                    {customer?.email}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span
                    className={`font-medium ${getThemeClasses("text-muted")}`}
                  >
                    Current Photo:
                  </span>
                  <span
                    className={`${getThemeClasses("text-primary")} flex items-center`}
                  >
                    <PhotoIcon className="w-4 h-4 mr-1" />
                    Exists
                  </span>
                </div>
              </div>
            </div>

            {/* Impact Information */}
            <div
              className={`${getThemeClasses("alert-info-bg")} border ${getThemeClasses("alert-info-border")} rounded-lg p-4 mb-6`}
            >
              <h4
                className={`text-sm font-semibold ${getThemeClasses("alert-info-text")} mb-2`}
              >
                What will happen:
              </h4>
              <ul
                className={`text-sm ${getThemeClasses("alert-info-text")} space-y-1 list-disc list-inside`}
              >
                <li>
                  The profile photo will be permanently removed from storage
                </li>
                <li>The customer's profile will display a default avatar</li>
                <li>This action cannot be reversed</li>
              </ul>
            </div>

            {/* Action Buttons */}
            <div
              className={`flex flex-col sm:flex-row gap-3 pt-6 border-t ${getThemeClasses("border-secondary")}`}
            >
              <Button
                type="button"
                onClick={() => navigate(`/admin/customer/${cid}/more/avatar`)}
                variant="outline"
                icon={ArrowLeftIcon}
                disabled={isDeleting}
                className="flex-1"
              >
                Cancel
              </Button>
              <Button
                type="button"
                onClick={handleDeleteAvatar}
                variant="danger"
                icon={TrashIcon}
                disabled={isDeleting}
                loading={isDeleting}
                className="flex-1"
              >
                {isDeleting ? "Deleting Photo..." : "Delete Photo Permanently"}
              </Button>
            </div>
          </FormCard>
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminCustomerDetailMoreAvatarDeletePage;
