'use client';

import { useState, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import { Search, UserPlus, Phone, MapPin, ChevronRight } from 'lucide-react';
import { api } from '@/lib/api';
import Link from 'next/link';
import { useDebounce } from '@/lib/hooks';

interface Client {
  id: string;
  firstName: string;
  lastName: string;
  email?: string;
  phone: string;
  address: string;
  accountNumber: string;
  isActive: boolean;
  subscriptions?: { status: string; plan?: { name: string; monthlyPrice: number } }[];
  createdAt: string;
}

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

function getSubStatus(client: Client): string {
  return client.subscriptions?.[0]?.status ?? 'NO_SUB';
}

const STATUS_COLORS: Record<string, string> = {
  ACTIVE: 'bg-emerald-100 text-emerald-700',
  PENDING: 'bg-yellow-100 text-yellow-700',
  SUSPENDED: 'bg-red-100 text-red-700',
  DISCONNECTED: 'bg-gray-100 text-gray-600',
  CANCELLED: 'bg-gray-100 text-gray-500',
  NO_SUB: 'bg-gray-100 text-gray-400',
};

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

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

  const clients: Client[] = Array.isArray(data) ? data : (data?.data ?? []);
  const total = (data as any)?.meta?.total ?? clients.length;

  return (
    <div>
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Clients</h1>
          <p className="text-slate-500 text-sm mt-1">
            {isLoading ? '...' : `${total} subscriber${total !== 1 ? 's' : ''}`}
          </p>
        </div>
        <Button style={{ backgroundColor: '#0891B2', color: 'white' }}>
          <UserPlus size={16} className="mr-2" />
          Add Client
        </Button>
      </div>

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

      {/* Table */}
      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Account #</TableHead>
                <TableHead>Name</TableHead>
                <TableHead>Phone</TableHead>
                <TableHead>Plan</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Address</TableHead>
                <TableHead className="w-10"></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 8 }).map((_, i) => (
                  <TableRow key={i}>
                    {Array.from({ length: 7 }).map((_, j) => (
                      <TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
                    ))}
                  </TableRow>
                ))
              ) : clients.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-12 text-slate-400">
                    {search ? `No clients matching "${search}"` : 'No clients yet'}
                  </TableCell>
                </TableRow>
              ) : (
                clients.map((c) => {
                  const subStatus = getSubStatus(c);
                  const planName = c.subscriptions?.[0]?.plan?.name ?? '—';
                  return (
                    <TableRow key={c.id} className="hover:bg-slate-50 cursor-pointer">
                      <TableCell className="font-mono text-sm text-slate-600">{c.accountNumber}</TableCell>
                      <TableCell className="font-medium">{c.firstName} {c.lastName}</TableCell>
                      <TableCell>
                        <span className="flex items-center gap-1 text-slate-500 text-sm">
                          <Phone size={12} />{c.phone}
                        </span>
                      </TableCell>
                      <TableCell className="text-sm text-slate-600">{planName}</TableCell>
                      <TableCell>
                        <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[subStatus] ?? STATUS_COLORS.NO_SUB}`}>
                          {subStatus.replace('_', ' ')}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="flex items-center gap-1 text-slate-400 text-xs max-w-[180px] truncate">
                          <MapPin size={10} />{c.address}
                        </span>
                      </TableCell>
                      <TableCell>
                        <Link href={`/clients/${c.id}`} className="text-slate-400 hover:text-slate-700">
                          <ChevronRight size={16} />
                        </Link>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Pagination */}
      {total > limit && (
        <div className="mt-4 flex items-center justify-between text-sm text-slate-500">
          <span>Page {page} of {Math.ceil(total / limit)}</span>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>
              Previous
            </Button>
            <Button variant="outline" size="sm" onClick={() => setPage(p => p + 1)} disabled={page * limit >= total}>
              Next
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
