import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, PencilIcon, TrashIcon, PlusIcon, MagnifyingGlassIcon } 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 } from '../lib/utils';
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="cell-user">
          {b.image_url ? (
            <img src={b.image_url} alt="" style={{ width: 40, height: 28, borderRadius: 6, objectFit: 'cover', flexShrink: 0 }} />
          ) : (
            <div style={{ width: 40, height: 28, borderRadius: 6, background: 'var(--surface-3)', flexShrink: 0 }} />
          )}
          <div>
            <b style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 220 }}>{b.title}</b>
          </div>
        </div>
      ),
    },
    { key: 'author', header: 'نویسنده', render: (b) => b.author?.name ?? '—' },
    {
      key: 'status',
      header: 'وضعیت',
      render: (b) => (
        <span className={`badge ${b.status === 'published' ? 'green' : 'gray'}`}>
          <span className="bdot" />
          {b.status === 'published' ? 'منتشرشده' : 'پیش‌نویس'}
        </span>
      ),
    },
    {
      key: 'tags',
      header: 'تگ‌ها',
      render: (b) => (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {b.tags?.slice(0, 3).map((tag, i) => (
            <span key={i} className="chip">{tag}</span>
          ))}
        </div>
      ),
    },
    { key: 'created_at', header: 'تاریخ', render: (b) => formatDate(b.created_at) },
  ];

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

  return (
    <div className="fade-in">
      <div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
        <div>
          <h1 className="section-title">بلاگ</h1>
          <div className="muted">{total} مقاله</div>
        </div>
        <button onClick={() => navigate('/admin/blogs/new')} className="btn primary sm">
          <PlusIcon style={{ width: 16, height: 16 }} />
          نوشتن مقاله
        </button>
      </div>

      <div className="card">
        <div className="card-pad" style={{ paddingBottom: 0 }}>
          <div className="toolbar">
            <div className="field" style={{ minWidth: 240 }}>
              <MagnifyingGlassIcon style={{ width: 17, height: 17 }} />
              <input
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                placeholder="جستجو بر اساس عنوان..."
              />
            </div>
            <div className="seg">
              {STATUS_FILTERS.map((f) => (
                <button
                  key={f.value}
                  className={statusFilter === f.value ? 'on' : ''}
                  onClick={() => { setStatusFilter(f.value); setPage(1); }}
                >
                  {f.label}
                </button>
              ))}
            </div>
          </div>
        </div>
        <DataTable<Blog>
          columns={columns}
          data={items}
          loading={isLoading}
          emptyMessage="هیچ مقاله‌ای یافت نشد"
          emptyAction={
            <button onClick={() => navigate('/admin/blogs/new')} className="btn primary sm">
              نوشتن اولین مقاله
            </button>
          }
          actions={(blog) => (
            <>
              <button onClick={() => navigate(`/admin/blogs/${blog.uuid}/edit`)}
                className="mini-btn" title="ویرایش">
                <PencilIcon style={{ width: 15, height: 15 }} />
              </button>
              <button onClick={() => setDeleteTarget(blog)}
                className="mini-btn danger" title="حذف">
                <TrashIcon style={{ width: 15, height: 15 }} />
              </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>
  );
}
