'use client';

import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { CheckCircle2, Clock3, Loader2, Search, ShieldCheck, Store, XCircle } from 'lucide-react';

interface SellerApplication {
  id: string;
  shopName: string;
  businessType: string;
  description: string;
  reason: string;
  experience?: string;
  website?: string;
  status: string;
  reviewNote?: string;
  createdAt: string;
  reviewedAt?: string;
  user?: {
    id: string;
    name?: string;
    email: string;
  };
}

const STATUS_CONFIG: Record<string, { label: string; className: string; icon: any }> = {
  PENDING: { label: 'Chờ duyệt', className: 'bg-amber-500/10 text-amber-400 border-amber-500/20', icon: Clock3 },
  APPROVED: { label: 'Đã duyệt', className: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20', icon: ShieldCheck },
  REJECTED: { label: 'Từ chối', className: 'bg-rose-500/10 text-rose-400 border-rose-500/20', icon: XCircle },
};

export default function AdminSellerApplicationsPage() {
  const [applications, setApplications] = useState<SellerApplication[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [toast, setToast] = useState<{ type: 'success' | 'error'; msg: string } | null>(null);
  const token = useAuthStore((s) => s.token);
  const LIMIT = 10;

  const showToast = (type: 'success' | 'error', msg: string) => {
    setToast({ type, msg });
    setTimeout(() => setToast(null), 3000);
  };

  const fetchApplications = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    try {
      const res = await api.get('/admin/seller-applications', {
        params: { page, limit: LIMIT, status: statusFilter || undefined },
      });
      const data = res.data?.data || [];
      const filtered = search
        ? data.filter((item: SellerApplication) => `${item.shopName} ${item.user?.name || ''} ${item.user?.email || ''}`.toLowerCase().includes(search.toLowerCase()))
        : data;
      setApplications(filtered);
      setTotal(res.data?.total || 0);
    } catch (error) {
      console.error(error);
      showToast('error', 'Không thể tải danh sách đơn đăng ký');
    } finally {
      setLoading(false);
    }
  }, [page, search, statusFilter, token]);

  useEffect(() => {
    const timer = window.setTimeout(() => { void fetchApplications(); }, 0);
    return () => window.clearTimeout(timer);
  }, [fetchApplications]);

  const handleApprove = async (id: string) => {
    if (!token) return;
    if (!confirm('Duyệt đơn này và cấp quyền Seller cho người dùng?')) return;
    setActionLoading(id);
    try {
      await api.patch(`/admin/seller-applications/${id}/approve`);
      showToast('success', 'Đơn đăng ký đã được duyệt');
      fetchApplications();
    } catch (error: any) {
      showToast('error', error?.response?.data?.message || 'Duyệt đơn thất bại');
    } finally {
      setActionLoading(null);
    }
  };

  const handleReject = async (id: string) => {
    if (!token) return;
    if (!confirm('Từ chối đơn này?')) return;
    setActionLoading(id);
    try {
      await api.patch(`/admin/seller-applications/${id}/reject`, { reason: 'Không phù hợp với quy định' });
      showToast('success', 'Đơn đăng ký đã bị từ chối');
      fetchApplications();
    } catch (error: any) {
      showToast('error', error?.response?.data?.message || 'Từ chối đơn thất bại');
    } finally {
      setActionLoading(null);
    }
  };

  const totalPages = Math.max(1, Math.ceil(total / LIMIT));
  const pendingCount = applications.filter((item) => item.status === 'PENDING').length;

  return (
    <div className="space-y-6">
      {toast && (
        <div className={`fixed right-6 top-6 z-50 rounded-xl border px-4 py-3 text-sm font-medium shadow-xl ${toast.type === 'success' ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-300' : 'border-rose-500/30 bg-rose-500/10 text-rose-300'}`}>
          {toast.msg}
        </div>
      )}

      <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Đơn xin làm Seller</h1>
          <p className="mt-1 text-sm text-gray-500">Duyệt và theo dõi các đơn đăng ký gian hàng từ người dùng.</p>
        </div>
        <div className="flex flex-col gap-3 md:flex-row">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500" />
            <input value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }} placeholder="Tìm tên shop / email" className="w-full rounded-xl border border-white/10 bg-[#141414] py-2.5 pl-10 pr-4 text-sm text-white md:w-72" />
          </div>
          <select value={statusFilter} onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }} className="rounded-xl border border-white/10 bg-[#141414] px-4 py-2.5 text-sm text-white">
            <option value="">Tất cả trạng thái</option>
            <option value="PENDING">Chờ duyệt</option>
            <option value="APPROVED">Đã duyệt</option>
            <option value="REJECTED">Từ chối</option>
          </select>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        {[{ label: 'Tổng đơn', value: total, icon: Store }, { label: 'Chờ duyệt', value: pendingCount, icon: Clock3 }, { label: 'Đã xử lý', value: applications.filter((item) => item.status !== 'PENDING').length, icon: CheckCircle2 }].map((item, index) => {
          const Icon = item.icon;
          return (
            <div key={index} className="rounded-2xl border border-white/10 bg-[#141414] p-4">
              <div className="flex items-center justify-between">
                <p className="text-sm text-gray-500">{item.label}</p>
                <Icon className="h-4 w-4 text-gray-400" />
              </div>
              <p className="mt-3 text-2xl font-black text-white">{item.value}</p>
            </div>
          );
        })}
      </div>

      <div className="overflow-hidden rounded-2xl border border-white/10 bg-[#141414]">
        <div className="grid grid-cols-12 gap-3 border-b border-white/10 px-5 py-3 text-xs font-bold uppercase tracking-wider text-gray-500">
          <div className="col-span-3">Người đăng ký</div>
          <div className="col-span-3">Gian hàng</div>
          <div className="col-span-2">Trạng thái</div>
          <div className="col-span-2">Ngày tạo</div>
          <div className="col-span-2 text-center">Hành động</div>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-20 text-gray-500">
            <Loader2 className="mr-2 h-5 w-5 animate-spin" />
            Đang tải dữ liệu...
          </div>
        ) : applications.length === 0 ? (
          <div className="py-20 text-center text-gray-500">Không có đơn đăng ký nào</div>
        ) : (
          applications.map((item) => {
            const config = STATUS_CONFIG[item.status] || STATUS_CONFIG.PENDING;
            const Icon = config.icon;
            return (
              <div key={item.id} className="grid grid-cols-12 gap-3 border-b border-white/5 px-5 py-4 last:border-0 hover:bg-white/[0.03]">
                <div className="col-span-3 min-w-0">
                  <p className="truncate text-sm font-semibold text-white">{item.user?.name || 'Ẩn danh'}</p>
                  <p className="truncate text-xs text-gray-500">{item.user?.email || '—'}</p>
                </div>
                <div className="col-span-3 min-w-0">
                  <p className="truncate text-sm font-semibold text-white">{item.shopName}</p>
                  <p className="truncate text-xs text-gray-500">{item.businessType}</p>
                </div>
                <div className="col-span-2">
                  <span className={`inline-flex items-center gap-1 rounded-full border px-2.5 py-1 text-[10px] font-bold ${config.className}`}>
                    <Icon className="h-3 w-3" />
                    {config.label}
                  </span>
                </div>
                <div className="col-span-2 text-sm text-gray-400">
                  <p>{new Date(item.createdAt).toLocaleDateString('vi-VN')}</p>
                  <p className="text-[11px] text-gray-600">{new Date(item.createdAt).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })}</p>
                </div>
                <div className="col-span-2 flex items-center justify-center gap-2">
                  {item.status === 'PENDING' ? (
                    <>
                      <button onClick={() => handleApprove(item.id)} disabled={actionLoading === item.id} className="rounded-lg border border-emerald-500/20 bg-emerald-500/10 px-3 py-1.5 text-xs font-semibold text-emerald-400 transition hover:bg-emerald-500/20 disabled:opacity-50">
                        {actionLoading === item.id ? <Loader2 className="h-3 w-3 animate-spin" /> : 'Duyệt'}
                      </button>
                      <button onClick={() => handleReject(item.id)} disabled={actionLoading === item.id} className="rounded-lg border border-rose-500/20 bg-rose-500/10 px-3 py-1.5 text-xs font-semibold text-rose-400 transition hover:bg-rose-500/20 disabled:opacity-50">
                        {actionLoading === item.id ? <Loader2 className="h-3 w-3 animate-spin" /> : 'Từ chối'}
                      </button>
                    </>
                  ) : (
                    <span className="text-xs text-gray-500">Đã xử lý</span>
                  )}
                </div>
              </div>
            );
          })
        )}
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between text-sm text-gray-500">
          <span>Trang {page} / {totalPages}</span>
          <div className="flex gap-2">
            <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page === 1} className="rounded-xl border border-white/10 bg-[#141414] px-3 py-2 disabled:opacity-40">←</button>
            <button onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={page === totalPages} className="rounded-xl border border-white/10 bg-[#141414] px-3 py-2 disabled:opacity-40">→</button>
          </div>
        </div>
      )}
    </div>
  );
}
