'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { 
  Users, 
  Search,
  Loader2,
  Phone,
  Mail,
  Building2,
  Clock,
  Package,
  ArrowRight,
  Shield,
  ShieldCheck,
  ShieldOff
} from 'lucide-react';

interface Customer {
  id: string;
  name: string;
  phone: string;
  email: string | null;
  company: string | null;
  is_admin: boolean;
  created_at: string;
  orderCount: number;
}

export default function AdminCustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [totalCustomers, setTotalCustomers] = useState(0);
  const [updatingAdminId, setUpdatingAdminId] = useState<string | null>(null);
  const [isAdmin, setIsAdmin] = useState(false);

  // 获取客户列表
  const fetchCustomers = async () => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) {
        params.set('search', search);
      }
      
      const response = await fetch(`/api/admin/customers?${params}`);
      const data = await response.json();
      if (response.ok) {
        setCustomers(data.customers || []);
        setTotalCustomers(data.total || 0);
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 检查当前管理员权限
  useEffect(() => {
    const checkAdmin = async () => {
      try {
        const response = await fetch('/api/admin/me');
        const data = await response.json();
        if (response.ok && data.admin) {
          setIsAdmin(data.admin.role === 'super_admin');
        }
      } catch (error) {
        console.error('Error checking admin:', error);
      }
    };
    checkAdmin();
  }, []);

  useEffect(() => {
    fetchCustomers();
  }, []);

  // 搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchCustomers();
  };

  // 切换管理员状态
  const handleToggleAdmin = async (customerId: string, currentStatus: boolean) => {
    setUpdatingAdminId(customerId);
    try {
      const response = await fetch(`/api/admin/customers/${customerId}/admin`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isAdmin: !currentStatus }),
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        // 更新本地状态
        setCustomers(prev => prev.map(c => 
          c.id === customerId ? { ...c, is_admin: !currentStatus } : c
        ));
      } else {
        alert(data.error || '操作失败');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('操作失败');
    } finally {
      setUpdatingAdminId(null);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">客户管理</h1>
          <p className="text-gray-500 mt-1">共 {totalCustomers} 位客户</p>
        </div>
      </div>

      {/* 搜索栏 */}
      <div className="bg-white rounded-2xl p-4 border border-gray-100 shadow-sm">
        <form onSubmit={handleSearch} className="flex gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="搜索姓名、手机号、公司..."
              className="w-full pl-10 pr-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <button
            type="submit"
            className="px-6 py-2.5 bg-blue-600 text-white font-medium rounded-xl hover:bg-blue-700 transition-colors"
          >
            搜索
          </button>
        </form>
      </div>

      {/* 客户列表 */}
      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
        </div>
      ) : customers.length === 0 ? (
        <div className="bg-white rounded-2xl p-12 border border-gray-100 text-center">
          <Users className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <p className="text-gray-500">暂无客户</p>
        </div>
      ) : (
        <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-100">
                <tr>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">客户信息</th>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">联系方式</th>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">公司</th>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">订单数</th>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">管理员</th>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">注册时间</th>
                  <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">操作</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {customers.map((customer) => (
                  <tr key={customer.id} className="hover:bg-gray-50/50 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center">
                          <span className="text-white font-semibold text-sm">
                            {customer.name.charAt(0)}
                          </span>
                        </div>
                        <div>
                          <div className="font-medium text-gray-900">{customer.name}</div>
                          <div className="text-xs text-gray-400">ID: {customer.id.slice(0, 8)}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                          <Phone className="w-4 h-4 text-gray-400" />
                          {customer.phone}
                        </div>
                        {customer.email && (
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <Mail className="w-4 h-4 text-gray-400" />
                            {customer.email}
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        {customer.company ? (
                          <>
                            <Building2 className="w-4 h-4 text-gray-400" />
                            {customer.company}
                          </>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <Package className="w-4 h-4 text-blue-500" />
                        <span className="font-medium text-gray-900">{customer.orderCount}</span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      {isAdmin ? (
                        <button
                          onClick={() => handleToggleAdmin(customer.id, customer.is_admin)}
                          disabled={updatingAdminId === customer.id}
                          className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-all ${
                            customer.is_admin
                              ? 'bg-green-100 text-green-700 hover:bg-green-200'
                              : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                          } disabled:opacity-50`}
                        >
                          {updatingAdminId === customer.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : customer.is_admin ? (
                            <ShieldCheck className="w-4 h-4" />
                          ) : (
                            <Shield className="w-4 h-4" />
                          )}
                          {customer.is_admin ? '管理员' : '设为管理员'}
                        </button>
                      ) : (
                        <div className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium ${
                          customer.is_admin
                            ? 'bg-green-100 text-green-700'
                            : 'bg-gray-100 text-gray-500'
                        }`}>
                          {customer.is_admin ? (
                            <>
                              <ShieldCheck className="w-4 h-4" />
                              管理员
                            </>
                          ) : (
                            <>
                              <ShieldOff className="w-4 h-4" />
                              普通用户
                            </>
                          )}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        <Clock className="w-4 h-4 text-gray-400" />
                        {formatDate(customer.created_at)}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <Link
                        href={`/admin/orders?search=${customer.phone}`}
                        className="inline-flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors"
                      >
                        查看订单
                        <ArrowRight className="w-4 h-4" />
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
