"use client";

import { useState, useMemo, useEffect, useCallback } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { CustomerTable } from "./customer-table";
import { CustomerDetailsDialog } from "./customer-details-dialog";
import { EditCustomerDialog } from "./edit-customer-dialog";
import { BlockCustomerDialog } from "./block-customer-dialog";
import { ChangePasswordDialog } from "../agents/change-password-dialog";
import {
  type Customer,
  type CustomerStatus,
} from "@/roles/admin/services/customers.service";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import {
  getUsersAction,
  changeUserStatusAction,
} from "@/features/users/actions/user-actions";
import { useAdminAuth } from "@/roles/admin/components/admin-auth-provider";
import { Loader2 } from "lucide-react";

/**
 * ✅ SAFE STATUS NORMALIZER
 */
function normalizeStatus(rawStatus: any): CustomerStatus {
  console.log("normalizeStatus input:", rawStatus, typeof rawStatus);

  if (!rawStatus) return "active";

  const status = String(rawStatus).toLowerCase().trim();

  if (status === "pending") {
    return "pending";
  }

  if (
    status === "block" ||
    status === "blocked" ||
    status === "inactive" ||
    status === "0" ||
    rawStatus === false ||
    rawStatus === 0
  ) {
    return "blocked";
  }

  return "active";
}

/**
 * ✅ MAP API USER → UI CUSTOMER
 */
function mapApiUserToCustomer(user: any): Customer {
  // Use the raw status if it's already a valid status, otherwise normalize it
  const validStatuses = ["active", "blocked", "pending"];
  const rawStatus = user.status?.toLowerCase()?.trim();

  const status = validStatuses.includes(rawStatus)
    ? (rawStatus as CustomerStatus)
    : normalizeStatus(user.status);

  return {
    id: String(user.id),

    firstName: user.first_name || "",
    lastName: user.last_name || "",

    email: user.email || "",
    phone: user.phone_number || "",

    status,

    totalBookings: 0,
    totalSpent: 0,

    joinedAt: user.created_at
      ? new Date(user.created_at).toISOString().split("T")[0]
      : "",

    lastActive: user.updated_at
      ? new Date(user.updated_at).toISOString().split("T")[0]
      : "",

    blockReason: user.reason_for_block || undefined,

    blockedAt:
      status === "blocked" ? user.updated_at?.split("T")[0] : undefined,

    bookings: [],
  };
}

export function CustomersClient() {
  const toast = useToastEnhanced();
  const { currentUser } = useAdminAuth();

  const [customers, setCustomers] = useState<Customer[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(
    null
  );
  const [isDetailsOpen, setIsDetailsOpen] = useState(false);

  const [isBlockDialogOpen, setIsBlockDialogOpen] = useState(false);
  const [customerToBlock, setCustomerToBlock] = useState<Customer | null>(null);

  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [customerToEdit, setCustomerToEdit] = useState<Customer | null>(null);

  const [isChangePasswordDialogOpen, setIsChangePasswordDialogOpen] =
    useState(false);
  const [customerToChangePassword, setCustomerToChangePassword] =
    useState<Customer | null>(null);

  /**
   * ✅ LOAD DATA
   */
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);

      const result = await getUsersAction(1, "customer");

      if (result.success && result.data?.data) {
        const mappedCustomers: Customer[] =
          result.data.data.map(mapApiUserToCustomer);

        setCustomers(mappedCustomers);
      } else {
        toast.error({
          title: "Error",
          description: result.error || "Failed to load customers",
        });
      }
    } catch (error) {
      console.error(error);

      toast.error({
        title: "Error",
        description: "Unexpected error occurred",
      });
    } finally {
      setIsLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  /**
   * FILTERS
   */
  const activeCustomers = useMemo(
    () => customers.filter((c) => c.status === "active"),
    [customers]
  );

  const blockedCustomers = useMemo(
    () => customers.filter((c) => c.status === "blocked"),
    [customers]
  );

  const pendingCustomers = useMemo(
    () => customers.filter((c) => c.status === "pending"),
    [customers]
  );

  /**
   * HANDLERS
   */
  const handleViewDetails = (customer: Customer) => {
    setSelectedCustomer(customer);
    setIsDetailsOpen(true);
  };

  const handleBlockClick = (customer: Customer) => {
    setCustomerToBlock(customer);
    setIsBlockDialogOpen(true);
  };

  const handleEditClick = (customer: Customer) => {
    setCustomerToEdit(customer);
    setIsEditDialogOpen(true);
  };

  const handleChangePasswordClick = (customer: Customer) => {
    setCustomerToChangePassword(customer);
    setIsChangePasswordDialogOpen(true);
  };

  const handleStatusChange = async (
    customerId: string,
    status: "active" | "block" | "pending",
    reasonBlock?: string,
    reasonReject?: string
  ) => {
    try {
      const result = await changeUserStatusAction({
        user_id: customerId,
        status,
        reason_for_block: reasonBlock,
        reason_for_reject: reasonReject,
      });

      if (result.success) {
        toast.success({
          title: "Success",
          description: `Customer status updated to ${status}`,
        });
        loadData(); // Reload data to reflect changes
      } else {
        toast.error({
          title: "Error",
          description: result.error || "Failed to update status",
        });
      }
    } catch {
      toast.error({
        title: "Error",
        description: "An unexpected error occurred",
      });
    }
  };

  const handleBlockCustomer = async (reason: string) => {
    if (!customerToBlock) return;

    await handleStatusChange(customerToBlock.id, "block", reason);

    setIsBlockDialogOpen(false);
    setCustomerToBlock(null);
  };

  const handleUnblockCustomer = async (customer: Customer) => {
    await handleStatusChange(customer.id, "active");
  };

  /**
   * UI
   */
  return (
    <section className="admin-section">
      <header className="admin-page-header">
        <div>
          <h1 className="admin-page-title">Customers</h1>

          <p className="admin-page-description">Manage customer accounts</p>
        </div>

        {currentUser && (
          <div className="px-3 py-1 bg-primary/10 rounded">
            Admin: {currentUser.name}
          </div>
        )}
      </header>

      {isLoading ? (
        <div className="flex justify-center py-20">
          <Loader2 className="animate-spin h-10 w-10" />
        </div>
      ) : (
        <Tabs defaultValue="all">
          <TabsList>
            <TabsTrigger value="all">All ({customers.length})</TabsTrigger>

            <TabsTrigger value="active">
              Active ({activeCustomers.length})
            </TabsTrigger>

            <TabsTrigger value="blocked">
              Blocked ({blockedCustomers.length})
            </TabsTrigger>

            <TabsTrigger value="pending">
              Pending ({pendingCustomers.length})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="all">
            <CustomerTable
              customers={customers}
              onViewDetails={handleViewDetails}
              onBlock={handleBlockClick}
              onUnblock={(customer) => handleUnblockCustomer(customer)}
              onEdit={handleEditClick}
              onChangePassword={handleChangePasswordClick}
            />
          </TabsContent>

          <TabsContent value="active">
            <CustomerTable
              customers={activeCustomers}
              onViewDetails={handleViewDetails}
              onBlock={handleBlockClick}
              onUnblock={(customer) => handleUnblockCustomer(customer)}
              onEdit={handleEditClick}
              onChangePassword={handleChangePasswordClick}
            />
          </TabsContent>

          <TabsContent value="blocked">
            <CustomerTable
              customers={blockedCustomers}
              onViewDetails={handleViewDetails}
              onBlock={handleBlockClick}
              onUnblock={(customer) => handleUnblockCustomer(customer)}
              onEdit={handleEditClick}
              onChangePassword={handleChangePasswordClick}
            />
          </TabsContent>

          <TabsContent value="pending">
            <CustomerTable
              customers={pendingCustomers}
              onViewDetails={handleViewDetails}
              onBlock={handleBlockClick}
              onUnblock={(customer) => handleUnblockCustomer(customer)}
              onEdit={handleEditClick}
              onChangePassword={handleChangePasswordClick}
            />
          </TabsContent>
        </Tabs>
      )}

      <CustomerDetailsDialog
        customer={selectedCustomer}
        open={isDetailsOpen}
        onOpenChange={setIsDetailsOpen}
      />

      <BlockCustomerDialog
        customer={customerToBlock}
        open={isBlockDialogOpen}
        onOpenChange={setIsBlockDialogOpen}
        onConfirm={handleBlockCustomer}
      />

      <EditCustomerDialog
        customer={customerToEdit}
        open={isEditDialogOpen}
        onOpenChange={setIsEditDialogOpen}
        onSuccess={loadData}
      />

      <ChangePasswordDialog
        agent={customerToChangePassword as any} // Reusing Agent dialog for Customer (fields are compatible: firstName, lastName, id)
        open={isChangePasswordDialogOpen}
        onOpenChange={setIsChangePasswordDialogOpen}
      />
    </section>
  );
}
