import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, PencilIcon, TrashIcon, PlusIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Blog } from '../types';
import { formatDate, formatNumber } 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';

const STATUS_FILTERS = [
  { value: '', label: 'همه' },
  { value: 'draft', label: 'پیش‌نویس' },
  { value: 'published', label: 'منتشرشده' },
];

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

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

  const deleteMutation = useMutation({
    mutationFn: (b: Blog) => api.delete<ApiResponse<null>>(`/api/v1/blog/${b.uuid}`),
    onSuccess: () => {
      toast.success('مقاله حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['blogs'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Blog>[] = [
    {
      key: 'title',
      header: 'عنوان',
      render: (b) => (
        <div className="flex items-center gap-3">
          {b.cover_image ? (
            <img src={b.cover_image} alt="" className="w-10 h-7 rounded object-cover shrink-0" />
          ) : (
            <div className="w-10 h-7 rounded bg-gray-100 shrink-0" />
          )}
          <span className="font-medium text-gray-900 line-clamp-1">{b.title}</span>
        </div>
      ),
    },
    { key: 'author_name', header: 'نویسنده' },
    {
      key: 'status',
      header: 'وضعیت',
      render: (b) => (
        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
          b.status === 'published'
            ? 'bg-green-100 text-green-700'
            : 'bg-gray-100 text-gray-600'
        }`}>
          {b.status === 'published' ? 'منتشرشده' : 'پیش‌نویس'}
        </span>
      ),
    },
    {
      key: 'tags',
      header: 'تگ‌ها',
      render: (b) => (
        <div className="flex flex-wrap gap-1">
          {b.tags?.slice(0, 3).map((tag, i) => (
            <span key={i} className="text-xs bg-blue-50 text-blue-600 px-2 py-0.5 rounded-full">{tag}</span>
          ))}
        </div>
      ),
    },
    { key: 'views_count', header: 'بازدید', render: (b) => formatNumber(b.views_count) },
    { key: 'published_at', header: 'انتشار', render: (b) => formatDate(b.published_at) },
    { key: 'created_at', header: 'تاریخ ثبت', render: (b) => formatDate(b.created_at) },
  ];

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

  return (
    <div>
      <PageHeader
        title="بلاگ"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'بلاگ' }]}
        action={
          <button onClick={() => navigate('/admin/blogs/new')}
            className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 transition-colors">
            <PlusIcon className="w-4 h-4" />
            نوشتن مقاله
          </button>
        }
      />

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <div className="flex items-center gap-3 mb-4">
          {STATUS_FILTERS.map((f) => (
            <button key={f.value} onClick={() => { setStatusFilter(f.value); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                statusFilter === f.value ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}>
              {f.label}
            </button>
          ))}
        </div>

        <DataTable<Blog>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس عنوان..."
          emptyMessage="هیچ مقاله‌ای یافت نشد"
          emptyAction={
            <button onClick={() => navigate('/admin/blogs/new')}
              className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 transition-colors">
              نوشتن اولین مقاله
            </button>
          }
          actions={(blog) => (
            <>
              <button onClick={() => navigate(`/admin/blogs/${blog.uuid}/edit`)}
                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(blog)}
                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?.title}" اطمینان دارید؟`}
        confirmLabel="حذف"
        danger
        loading={deleteMutation.isPending}
        onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
