// components/admin/trusted-client/TrustedClientTable.tsx
'use client';

import * as React from 'react';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
import { TrustedClient } from '@/lib/modules/trusted-client/trusted-client.types';
import { BasicDataGrid } from '@/components/table/BasicDataGridTable';
import { useGetAllTrustedClientsQuery } from '@/store/slice/trustedClientApi';
import TrustedClientForm from './TrustedClientForm';
import { DeleteClientDialog } from './DeleteClients';
import { trustedClientColumns } from './trustedClientColumns';
import StatsCards from './StatsCards';
import { useSelector } from 'react-redux';
import { isAdminSelector } from '@/store/authSlice';
// Main component
function TrustedClientTable() {
	const isAdmin = useSelector(isAdminSelector);
	const router = useRouter();
	const pathname = usePathname();
	const searchParams = useSearchParams();
	const [openDialog, setOpenDialog] = React.useState(false);
	const [client, setClient] = React.useState<TrustedClient | null>(null);
	const [isDeleting, setIsDeleting] = React.useState(false);
	const [DeletingClient, setDeletingClient] =
		React.useState<TrustedClient | null>(null);
	// Get params from URL
	const page = parseInt(searchParams.get('page') || '1');
	const search = searchParams.get('search') || '';

	// Update URL with new params
	const updateSearchParams = (updates: Record<string, string>) => {
		const params = new URLSearchParams(searchParams.toString());

		Object.entries(updates).forEach(([key, value]) => {
			if (value) {
				params.set(key, value);
			} else {
				params.delete(key);
			}
		});

		// Reset to page 1 when search or filters change
		if (updates.search !== undefined) params.set('page', '1');

		router.push(`${pathname}?${params.toString()}`);
	};

	// Fetch data with RTK Query
	const { data } = useGetAllTrustedClientsQuery();

	// Handlers
	const handleSearch = (query: string) => {
		updateSearchParams({ search: query });
	};

	const handlePageChange = (newPage: number) => {
		updateSearchParams({ page: newPage.toString() });
	};

	const handleItemsPerPageChange = (newLimit: number) => {
		updateSearchParams({
			limit: newLimit.toString(),
			page: '1', // Reset to first page
		});
	};

	const handleEdit = (client: TrustedClient) => {
		setClient(client);
		setOpenDialog(true);
		// Navigate to edit page or open modal
	};

	const handleDelete = (client: TrustedClient) => {
		setIsDeleting(true);
		setDeletingClient(client);
		// Show confirmation and delete
	};

	const handleView = (client: TrustedClient) => {
		console.log('Viewing client:', client);
		// Navigate to detail page
	};

	const handleAdd = () => {
		setOpenDialog(true);
	};

	// Get data from response
	const tableData = data?.data || [];
	const paginationMeta = data?.pagnation;

	return (
		<>
			<div className="">
				{/* Main container with proper padding */}
				<div className="px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-10 max-w-[1600px] mx-auto">
					{/* Header Section with refined spacing */}
					<div className="mb-8 lg:mb-10">
						<div className="flex flex-col md:flex-row md:items-end md:justify-between gap-4">
							<div className="space-y-3">
								{/* Title with gold accent */}
								<div className="relative">
									<h1
										className="font-playfair text-3xl sm:text-4xl lg:text-5xl font-bold tracking-tight"
										style={{ color: '#E5D9C6' }}
									>
										Trusted Clients
									</h1>
									<div className="luxury-line w-24 mt-2" />
								</div>

								{/* Description with proper spacing */}
								<p
									className="font-inter text-sm sm:text-base max-w-2xl"
									style={{ color: '#B8B2A8' }}
								>
									Manage your premium client partnerships and
									relationships
								</p>
							</div>
						</div>
					</div>

					{/* Stats Cards Section with balanced spacing */}
					<div className="mb-8 lg:mb-10">
						{data && <StatsCards stats={data?.stats} />}
					</div>

					{/* Table Section with proper top margin */}
					<div className="mt-6 lg:mt-8">
						<div className="space-y-4">
							<BasicDataGrid
								data={tableData}
								columns={trustedClientColumns}
								searchPlaceholder="Search clients by name or website..."
								showSearch={true}
								showPagination={true}
								showAddButton={true}
								showActions={true}
								currentPage={page}
								totalPages={paginationMeta?.totalPages || 1}
								onPageChange={handlePageChange}
								onItemPerPageChange={handleItemsPerPageChange}
								onSearch={handleSearch}
								initialSearchValue={search}
								onAddClick={handleAdd}
								onEdit={handleEdit}
								onView={handleView}
								onDelete={isAdmin ? handleDelete : undefined}
								buttonTitle="Add Client"
							/>
						</div>
						<TrustedClientForm
							isEditing={client !== null}
							isDialogOpen={openDialog}
							setIsDialogOpen={setOpenDialog}
							client={client}
							setEditClient={setClient}
						/>
						{DeletingClient && (
							<DeleteClientDialog
								isOpen={isDeleting}
								client={DeletingClient}
								setIsOpen={setIsDeleting}
							/>
						)}
					</div>
				</div>
			</div>
		</>
	);
}

export default TrustedClientTable;
