// src/pages/Admin/Setting/InactiveClient/Detail/Page.jsx

import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useCustomerManager } from "../../../../../services/Services";
import {
  Card,
  Button,
  Alert,
  Loading,
  Breadcrumb,
  Badge,
  EmptyState,
  BackToListButton,
  EditButton,
  SystemInfo,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  ChartBarIcon,
  Cog6ToothIcon,
  ArchiveBoxIcon,
  AcademicCapIcon,
  HeartIcon,
  BuildingOfficeIcon,
  BuildingOffice2Icon,
  UserGroupIcon,
  EnvelopeIcon,
  PhoneIcon,
  CalendarIcon,
  UserIcon,
  EyeIcon,
  PencilSquareIcon,
  ArrowPathIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";
import {
  CUSTOMER_TYPE_VALUES,
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_STATUS,
  CUSTOMER_STATUS_LABELS,
  CUSTOMER_DEACTIVATION_REASONS,
  CUSTOMER_DEACTIVATION_REASON_LABELS,
} from "../../../../../constants/Customer";

function SettingInactiveClientDetailPage() {
  return (
    <UIXThemeProvider>
      <SettingInactiveClientDetailPageContent />
    </UIXThemeProvider>
  );
}

const SettingInactiveClientDetailPageContent = memo(
  function SettingInactiveClientDetailPageContent() {
    const navigate = useNavigate();
    const { id } = useParams();
    const customerManager = useCustomerManager();
    const { getThemeClasses } = useUIXTheme();

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
        linkText: getThemeClasses("text-primary"),
        linkHover: getThemeClasses("text-primary-hover"),
        textMuted: getThemeClasses("text-muted"),
      }),
      [getThemeClasses],
    );

    // State management
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [successMessage, setSuccessMessage] = useState("");
    const [inactiveClient, setInactiveClient] = useState(null);

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

    // Fetch inactive client details
    const fetchInactiveClientDetail = useCallback(async () => {
      try {
        setIsLoading(true);
        setError(null);

        const response = await customerManager.getCustomerById(
          id,
          onUnauthorized,
        );

        // Verify this is actually an inactive client
        if (response.status !== CUSTOMER_STATUS.INACTIVE) {
          setError("This client is not inactive");
          return;
        }

        setInactiveClient(response);
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("Failed to fetch inactive client detail:", err);
          setError(err.message || "Failed to load inactive client details");
        }
      } finally {
        setIsLoading(false);
      }
    }, [id, customerManager, onUnauthorized]);

    // Load data on component mount
    useEffect(() => {
      // Explicitly scroll to top when component mounts
      window.scrollTo(0, 0);
      if (id) {
        fetchInactiveClientDetail();
      } else {
        setError("Invalid client ID");
        setIsLoading(false);
      }
    }, [id, fetchInactiveClientDetail]);

    // Handle URL state (success message from other pages)
    useEffect(() => {
      const urlParams = new URLSearchParams(window.location.search);
      const message = urlParams.get("success");
      if (message) {
        setSuccessMessage(message);
        // Clear the URL parameter
        window.history.replaceState({}, "", window.location.pathname);
        // Clear success message after 3 seconds
        setTimeout(() => setSuccessMessage(""), 3000);
      }
    }, []);

    // Breadcrumb items - memoized
    const breadcrumbItems = useMemo(
      () => [
        { label: "Dashboard", href: "/admin/dashboard", icon: ChartBarIcon },
        { label: "Settings", href: "/admin/settings", icon: Cog6ToothIcon },
        {
          label: "Inactive Clients",
          href: "/admin/settings/inactive-clients",
          icon: ArchiveBoxIcon,
        },
        { label: inactiveClient?.name || "Details" },
      ],
      [inactiveClient?.name],
    );

    // Get customer type icon
    const getCustomerTypeIcon = (type) => {
      switch (type) {
        case CUSTOMER_TYPE_VALUES.EDUCATIONAL:
          return <AcademicCapIcon className="w-5 h-5" />;
        case CUSTOMER_TYPE_VALUES.CORPORATE:
          return <BuildingOffice2Icon className="w-5 h-5" />;
        case CUSTOMER_TYPE_VALUES.NON_PROFIT:
          return <HeartIcon className="w-5 h-5" />;
        case CUSTOMER_TYPE_VALUES.GOVERNMENT:
          return <BuildingOfficeIcon className="w-5 h-5" />;
        default:
          return <UserGroupIcon className="w-5 h-5" />;
      }
    };

    // Get type badge color
    const getTypeBadgeColor = (customerType) => {
      switch (customerType) {
        case CUSTOMER_TYPE_VALUES.EDUCATIONAL:
          return "info";
        case CUSTOMER_TYPE_VALUES.CORPORATE:
          return "success";
        case CUSTOMER_TYPE_VALUES.NON_PROFIT:
          return "primary";
        case CUSTOMER_TYPE_VALUES.GOVERNMENT:
          return "warning";
        default:
          return "default";
      }
    };

    // Format deactivation reason for display
    const getDeactivationReasonText = (reason, reasonOther) => {
      if (reason === CUSTOMER_DEACTIVATION_REASONS.OTHER && reasonOther) {
        return reasonOther;
      }
      return CUSTOMER_DEACTIVATION_REASON_LABELS[reason] || "Not specified";
    };

    if (isLoading) {
      return (
        <div
          className={`min-h-screen ${themeClasses.bgGradientPrimary} flex items-center justify-center`}
        >
          <Loading size="lg" text="Loading inactive client details..." />
        </div>
      );
    }

    if (error || !inactiveClient) {
      return (
        <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <Breadcrumb items={breadcrumbItems.slice(0, -1)} />
            <div className="mt-8">
              <EmptyState
                icon={ExclamationTriangleIcon}
                title={error || "Inactive client not found"}
                description="The client you're looking for could not be found or is not inactive."
                action={
                  <Button
                    variant="primary"
                    onClick={() => navigate("/admin/settings/inactive-clients")}
                  >
                    ← Back to Inactive Clients
                  </Button>
                }
              />
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <Breadcrumb items={breadcrumbItems} className="mb-8" />

          <div className="mb-8 flex justify-between items-center">
            <div className="flex items-center gap-3">
              {getCustomerTypeIcon(inactiveClient.type)}
              <h1 className={`text-3xl font-bold ${themeClasses.linkText}`}>
                {inactiveClient.name}
              </h1>
            </div>
            <div className="flex gap-2">
              <EditButton
                onClick={() =>
                  navigate(`/admin/settings/inactive-clients/${id}/update`)
                }
                text="Edit Status"
              />
              <Button
                variant="primary"
                onClick={() => navigate(`/admin/customers/${id}`)}
              >
                <EyeIcon className="w-4 h-4 mr-2" />
                View Full Profile
              </Button>
            </div>
          </div>

          {error && (
            <Alert
              type="error"
              dismissible
              onDismiss={() => setError(null)}
              className="mb-6"
            >
              {error}
            </Alert>
          )}

          {successMessage && (
            <Alert
              type="success"
              dismissible
              onDismiss={() => setSuccessMessage("")}
              className="mb-6"
            >
              {successMessage}
            </Alert>
          )}

          {/* Status Alert */}
          <Alert type="warning" className="mb-6">
            <div className="flex items-start">
              <ExclamationTriangleIcon className="w-5 h-5 mr-2 flex-shrink-0" />
              <div>
                <strong>Inactive Client:</strong> This client has been archived
                and is no longer active in the system.
              </div>
            </div>
          </Alert>

          {/* Basic Information Card */}
          <Card className="mb-6">
            <h2 className="text-lg font-semibold mb-4">Basic Information</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <h3 className="text-base font-medium text-gray-700 mb-3">
                  Personal Details
                </h3>
                <div className="space-y-3">
                  <div>
                    <label className="text-sm font-medium text-gray-600">
                      Name
                    </label>
                    <p className="mt-1 text-base">{inactiveClient.name}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-600">
                      Customer Type
                    </label>
                    <div className="mt-1">
                      <Badge variant={getTypeBadgeColor(inactiveClient.type)}>
                        {CUSTOMER_TYPE_LABELS[inactiveClient.type] ||
                          inactiveClient.type}
                      </Badge>
                    </div>
                  </div>
                  {inactiveClient.size && (
                    <div>
                      <label className="text-sm font-medium text-gray-600">
                        Size
                      </label>
                      <p className="mt-1 text-base">{inactiveClient.size}</p>
                    </div>
                  )}
                </div>
              </div>

              <div>
                <h3 className="text-base font-medium text-gray-700 mb-3">
                  Contact Information
                </h3>
                <div className="space-y-3">
                  <div>
                    <label className="text-sm font-medium text-gray-600">
                      Email
                    </label>
                    <p className="mt-1 text-base">
                      {inactiveClient.email ? (
                        <a
                          href={`mailto:${inactiveClient.email}`}
                          className={`${themeClasses.linkText} ${themeClasses.linkHover} flex items-center`}
                        >
                          <EnvelopeIcon className="w-4 h-4 mr-1" />
                          {inactiveClient.email}
                        </a>
                      ) : (
                        <span className={themeClasses.textMuted}>
                          Not provided
                        </span>
                      )}
                    </p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-600">
                      Phone
                    </label>
                    <p className="mt-1 text-base">
                      {inactiveClient.phone ? (
                        <a
                          href={`tel:${inactiveClient.phone}`}
                          className={`${themeClasses.linkText} ${themeClasses.linkHover} flex items-center`}
                        >
                          <PhoneIcon className="w-4 h-4 mr-1" />
                          {inactiveClient.phone}
                        </a>
                      ) : (
                        <span className={themeClasses.textMuted}>
                          Not provided
                        </span>
                      )}
                    </p>
                  </div>
                  {inactiveClient.address && (
                    <div>
                      <label className="text-sm font-medium text-gray-600">
                        Address
                      </label>
                      <p className="mt-1 text-base">{inactiveClient.address}</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </Card>

          {/* Deactivation Information Card */}
          <Card className="mb-6 border-l-4 border-orange-500">
            <h2 className="text-lg font-semibold mb-4">
              Deactivation Information
            </h2>
            <div className="space-y-4">
              <div>
                <label className="text-sm font-medium text-gray-600">
                  Status
                </label>
                <div className="mt-1">
                  <Badge variant="error" size="lg">
                    🚫 Inactive (Archived)
                  </Badge>
                </div>
              </div>

              <div>
                <label className="text-sm font-medium text-gray-600">
                  Deactivation Reason
                </label>
                <p className="mt-1 text-base">
                  {getDeactivationReasonText(
                    inactiveClient.deactivationReason,
                    inactiveClient.deactivationReasonOther,
                  )}
                </p>
              </div>

              {inactiveClient.description && (
                <div>
                  <label className="text-sm font-medium text-gray-600">
                    Notes
                  </label>
                  <p className="mt-1 text-base text-gray-700 whitespace-pre-wrap">
                    {inactiveClient.description}
                  </p>
                </div>
              )}
            </div>
          </Card>

          {/* System Information Card */}
          <Card className="mb-6">
            <SystemInfo
              createdAt={inactiveClient.createdAt}
              createdByUserName={inactiveClient.createdBy}
              createdFromIpAddress={inactiveClient.createdFromIpAddress}
              modifiedAt={inactiveClient.updatedAt}
              modifiedByUserName={inactiveClient.updatedBy}
              modifiedFromIpAddress={inactiveClient.modifiedFromIpAddress}
            />
          </Card>

          {/* Action Buttons */}
          <Card>
            <div className="flex flex-wrap gap-3 justify-center">
              <BackToListButton
                onClick={() => navigate("/admin/settings/inactive-clients")}
                text="Back to Inactive Clients"
              />
              <EditButton
                onClick={() =>
                  navigate(`/admin/settings/inactive-clients/${id}/update`)
                }
                text="Edit Status & Reason"
                variant="primary"
              />
              <Button
                variant="secondary"
                onClick={() => navigate(`/admin/customers/${id}`)}
              >
                <EyeIcon className="w-4 h-4 mr-2" />
                View Full Client Profile
              </Button>
              <Button
                variant="success"
                onClick={() => navigate(`/admin/customers/${id}/edit`)}
              >
                <ArrowPathIcon className="w-4 h-4 mr-2" />
                Reactivate Client
              </Button>
            </div>
          </Card>
        </div>
      </div>
    );
  },
);
SettingInactiveClientDetailPageContent.displayName =
  "SettingInactiveClientDetailPageContent";

export default SettingInactiveClientDetailPage;
