import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { CheckIcon, TrashIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Comment } from '../types';
import { formatDate } 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';

const FILTERS = [
  { value: '', label: 'همه' },
  { value: 'pending', label: 'در انتظار تأیید' },
  { value: 'approved', label: 'تأییدشده' },
];

export default function CommentsPage() {
  const qc = useQueryClient();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [approvedFilter, setApprovedFilter] = useState('pending');
  const [deleteTarget, setDeleteTarget] = useState<Comment | null>(null);
  const limit = 15;

  const { data, isLoading } = useQuery({
    queryKey: ['comments', page, search, approvedFilter],
    queryFn: () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.set('search', search);
      if (approvedFilter !== '') params.set('status', approvedFilter);
      return api.get<PaginatedResponse<Comment>>(`/api/v1/admin/comments?${params}`);
    },
  });

  const approveMutation = useMutation({
    mutationFn: (c: Comment) => api.post<ApiResponse<null>>(`/api/v1/admin/comment/${c.uuid}/approve`, {}),
    onSuccess: () => {
      toast.success('نظر تأیید شد');
      qc.invalidateQueries({ queryKey: ['comments'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const deleteMutation = useMutation({
    mutationFn: (c: Comment) => api.delete<ApiResponse<null>>(`/api/v1/comment/${c.uuid}`),
    onSuccess: () => {
      toast.success('نظر حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['comments'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Comment>[] = [
    {
      key: 'patient_name',
      header: 'کاربر',
      render: (c) => <span className="font-medium text-gray-900">{c.patient_name}</span>,
    },
    { key: 'doctor_name', header: 'پزشک', render: (c) => `دکتر ${c.doctor_name}` },
    { key: 'title', header: 'عنوان' },
    {
      key: 'body',
      header: 'متن',
      render: (c) => (
        <span className="text-gray-500 text-xs line-clamp-2 max-w-xs">{c.body}</span>
      ),
    },
    {
      key: 'is_approved',
      header: 'وضعیت',
      render: (c) => <ActiveBadge active={c.is_approved} />,
    },
    { key: 'created_at', header: 'تاریخ', render: (c) => formatDate(c.created_at) },
  ];

  const items = data?.data ?? [];
  const total = data?.meta?.totalRecords ?? 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">
        <div className="flex items-center gap-3 mb-4">
          {FILTERS.map((f) => (
            <button key={f.value} onClick={() => { setApprovedFilter(f.value); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                approvedFilter === f.value ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}>
              {f.label}
            </button>
          ))}
        </div>

        <DataTable<Comment>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس نام پزشک یا متن..."
          emptyMessage="هیچ نظری یافت نشد"
          actions={(comment) => (
            <>
              {!comment.is_approved && (
                <button onClick={() => approveMutation.mutate(comment)}
                  className="p-1.5 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors" title="تأیید">
                  <CheckIcon className="w-4 h-4" />
                </button>
              )}
              <button onClick={() => setDeleteTarget(comment)}
                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="آیا از حذف این نظر اطمینان دارید؟"
        confirmLabel="حذف"
        danger
        loading={deleteMutation.isPending}
        onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
