'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Search, UserPlus, ChevronRight } from 'lucide-react';

interface Client {
  id: string;
  accountNumber: string;
  firstName: string;
  lastName: string;
  phone: string;
  isActive: boolean;
  area: { name: string } | null;
  subscriptions: Array<{
    status: string;
    type: string;
    monthlyPrice: string;
    plan?: { name: string };
  }>;
}

interface ClientsResponse {
  data: Client[];
  total: number;
  page: number;
  limit: number;
}

const statusColors: Record<string, string> = {
  ACTIVE: 'bg-green-100 text-green-700',
  PENDING: 'bg-yellow-100 text-yellow-700',
  SUSPENDED: 'bg-red-100 text-red-700',
  DISCONNECTED: 'bg-gray-100 text-gray-700',
  CANCELLED: 'bg-gray-100 text-gray-500',
};

export default function ClientsPage() {
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);

  const { data, isLoading } = useQuery<ClientsResponse>({
    queryKey: ['clients', search, page],
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), limit: '20' });
      if (search) params.set('search', search);
      const res = await api.get(`/api/v1/clients?${params}`);
      return res.data;
    },
    staleTime: 30_000,
  });

  const clients = data?.data ?? [];
  const total = data?.total ?? 0;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Clients</h1>
          <p className="text-slate-500 text-sm mt-1">{total} total clients</p>
        </div>
        <button
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white"
          style={{ backgroundColor: '#0891B2' }}
        >
          <UserPlus size={16} />
          Add Client
        </button>
      </div>

      {/* Search */}
      <div className="relative mb-4">
        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
        <Input
          placeholder="Search by name or account number..."
          className="pl-9"
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }}
        />
      </div>

      {/* Table */}
      <Card className="border shadow-sm">
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-slate-50">
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Account #</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Name</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Area</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Plan</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Status</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden xl:table-cell">Monthly</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody>
                {isLoading
                  ? Array.from({ length: 8 }).map((_, i) => (
                      <tr key={i} className="border-b">
                        <td className="px-4 py-3"><Skeleton className="h-4 w-24" /></td>
                        <td className="px-4 py-3"><Skeleton className="h-4 w-32" /></td>
                        <td className="px-4 py-3 hidden md:table-cell"><Skeleton className="h-4 w-20" /></td>
                        <td className="px-4 py-3 hidden lg:table-cell"><Skeleton className="h-4 w-24" /></td>
                        <td className="px-4 py-3"><Skeleton className="h-5 w-16 rounded-full" /></td>
                        <td className="px-4 py-3 hidden xl:table-cell"><Skeleton className="h-4 w-16" /></td>
                        <td className="px-4 py-3"><Skeleton className="h-4 w-4" /></td>
                      </tr>
                    ))
                  : clients.map((client) => {
                      const sub = client.subscriptions?.[0];
                      const status = sub?.status ?? (client.isActive ? 'ACTIVE' : 'INACTIVE');
                      return (
                        <tr
                          key={client.id}
                          className="border-b hover:bg-slate-50 cursor-pointer transition-colors"
                        >
                          <td className="px-4 py-3 font-mono text-xs text-slate-600">
                            {client.accountNumber}
                          </td>
                          <td className="px-4 py-3 font-medium text-slate-800">
                            {client.firstName} {client.lastName}
                            <div className="text-xs text-slate-400">{client.phone}</div>
                          </td>
                          <td className="px-4 py-3 text-slate-600 hidden md:table-cell">
                            {client.area?.name ?? '—'}
                          </td>
                          <td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
                            {sub?.plan?.name ?? (sub ? `${sub.type}` : '—')}
                          </td>
                          <td className="px-4 py-3">
                            <span
                              className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[status] ?? 'bg-gray-100 text-gray-500'}`}
                            >
                              {status}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-slate-600 hidden xl:table-cell">
                            {sub ? `₱${Number(sub.monthlyPrice).toLocaleString()}` : '—'}
                          </td>
                          <td className="px-4 py-3 text-slate-400">
                            <ChevronRight size={16} />
                          </td>
                        </tr>
                      );
                    })}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {total > 20 && (
            <div className="flex items-center justify-between px-4 py-3 border-t">
              <p className="text-sm text-slate-500">
                Showing {(page - 1) * 20 + 1}–{Math.min(page * 20, total)} of {total}
              </p>
              <div className="flex gap-2">
                <button
                  disabled={page === 1}
                  onClick={() => setPage(p => p - 1)}
                  className="px-3 py-1 text-sm border rounded-md disabled:opacity-40"
                >
                  Prev
                </button>
                <button
                  disabled={page * 20 >= total}
                  onClick={() => setPage(p => p + 1)}
                  className="px-3 py-1 text-sm border rounded-md disabled:opacity-40"
                >
                  Next
                </button>
              </div>
            </div>
          )}

          {!isLoading && clients.length === 0 && (
            <div className="text-center py-12 text-slate-400">
              No clients found{search ? ` for "${search}"` : ''}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
