import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, TrashIcon, PencilIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { User } from '../types';
import { formatDate, maskMobile } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import { ActiveBadge } from '../components/ui/StatusBadge';
import Pagination from '../components/ui/Pagination';
import ConfirmDialog from '../components/ui/ConfirmDialog';

export default function UsersPage() {
  const navigate = useNavigate();
  const qc = useQueryClient();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [deleteTarget, setDeleteTarget] = useState<User | null>(null);
  const limit = 15;

  const { data, isLoading } = useQuery({
    queryKey: ['users', page, search],
    queryFn: () =>
      api.get<PaginatedResponse<User>>(
        `/api/v1/users?page=${page}&limit=${limit}${search ? `&search=${encodeURIComponent(search)}` : ''}`,
      ),
  });

  const deleteMutation = useMutation({
    mutationFn: (user: User) => api.delete<ApiResponse<null>>(`/api/v1/user/${user.id}`),
    onSuccess: () => {
      toast.success('کاربر حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['users'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<User>[] = [
    {
      key: 'name',
      header: 'نام',
      render: (u) => (
        <span className="font-medium text-gray-900">
          {u.first_name || u.last_name
            ? `${u.first_name ?? ''} ${u.last_name ?? ''}`.trim()
            : '—'}
        </span>
      ),
    },
    {
      key: 'mobile_number',
      header: 'موبایل',
      render: (u) => <span dir="ltr">{maskMobile(u.mobile_number)}</span>,
    },
    {
      key: 'roles',
      header: 'نقش',
      render: (u) => (
        <span className="text-xs bg-gray-100 text-gray-700 px-2 py-0.5 rounded-full">
          {u.roles.includes('ROLE_ADMIN')
            ? 'ادمین'
            : u.roles.includes('ROLE_DOCTOR')
              ? 'پزشک'
              : 'کاربر'}
        </span>
      ),
    },
    {
      key: 'is_active',
      header: 'وضعیت',
      render: (u) => <ActiveBadge active={u.is_active} />,
    },
    {
      key: 'created_at',
      header: 'تاریخ ثبت',
      render: (u) => formatDate(u.created_at),
    },
  ];

  const items = data?.data?.items ?? [];
  const total = data?.data?.total ?? 0;

  return (
    <div>
      <PageHeader
        title="کاربران"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'کاربران' }]}
      />

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <DataTable<User>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس نام یا موبایل..."
          emptyMessage="هیچ کاربری یافت نشد"
          actions={(user) => (
            <>
              <button
                onClick={() => navigate(`/admin/users/${user.uuid}`)}
                className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                title="مشاهده"
              >
                <EyeIcon className="w-4 h-4" />
              </button>
              <button
                onClick={() => navigate(`/admin/users/${user.uuid}?edit=1`)}
                className="p-1.5 text-gray-400 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors"
                title="ویرایش"
              >
                <PencilIcon className="w-4 h-4" />
              </button>
              <button
                onClick={() => setDeleteTarget(user)}
                className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                title="حذف"
              >
                <TrashIcon className="w-4 h-4" />
              </button>
            </>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>

      <ConfirmDialog
        open={!!deleteTarget}
        title="حذف کاربر"
        message={`آیا از حذف کاربر "${deleteTarget?.first_name ?? deleteTarget?.mobile_number}" اطمینان دارید؟ این عمل قابل بازگشت نیست.`}
        confirmLabel="حذف"
        danger
        loading={deleteMutation.isPending}
        onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
