import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { TrashIcon, StarIcon } from '@heroicons/react/24/outline';
import { StarIcon as StarSolid } from '@heroicons/react/24/solid';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Rating } from '../types';
import { formatDate } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import Pagination from '../components/ui/Pagination';
import ConfirmDialog from '../components/ui/ConfirmDialog';

function Stars({ value }: { value: number }) {
  return (
    <div className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map((i) => (
        i <= value
          ? <StarSolid key={i} className="w-3.5 h-3.5 text-yellow-400" />
          : <StarIcon key={i} className="w-3.5 h-3.5 text-gray-300" />
      ))}
      <span className="text-xs text-gray-500 mr-1">{value}</span>
    </div>
  );
}

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

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

  const deleteMutation = useMutation({
    mutationFn: (r: Rating) => api.delete<ApiResponse<null>>(`/api/v1/rate/${r.uuid}`),
    onSuccess: () => {
      toast.success('امتیاز حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['ratings'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Rating>[] = [
    { key: 'patient_name', header: 'بیمار', render: (r) => <span className="font-medium">{r.patient_name}</span> },
    { key: 'doctor_name', header: 'پزشک', render: (r) => `دکتر ${r.doctor_name}` },
    { key: 'overall', header: 'کلی', render: (r) => <Stars value={r.overall} /> },
    { key: 'diagnosis_accuracy', header: 'صحت تشخیص', render: (r) => <Stars value={r.diagnosis_accuracy} /> },
    { key: 'skill', header: 'مهارت', render: (r) => <Stars value={r.skill} /> },
    { key: 'behavior', header: 'رفتار', render: (r) => <Stars value={r.behavior} /> },
    { key: 'created_at', header: 'تاریخ', render: (r) => formatDate(r.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">
        <DataTable<Rating>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس نام پزشک..."
          emptyMessage="هیچ امتیازی یافت نشد"
          actions={(rating) => (
            <button onClick={() => setDeleteTarget(rating)}
              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>
  );
}
