"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

interface Client {
  id: string;
  firstName: string;
  lastName: string;
  email: string | null;
  phone: string | null;
  avatar?: string | null;
  level: string | null;
  notes: string | null;
  isActive: boolean;
  createdAt: string;
  memberships?: Array<{
    id: string;
    status: string;
    startDate: string;
    endDate: string;
    remainingHours: number | null;
    plan: {
      id: string;
      name: string;
      price: number | string;
      durationMonths: number;
      courtHours: number | null;
      discountPercent: number | string | null;
    };
  }>;
  _count?: {
    bookings: number;
  };
  stats?: {
    totalBookings: number;
    totalSpent: number;
    balance: number;
  };
}

interface ClientTableProps {
  clients: Client[];
  onRowClick?: (client: Client) => void;
  onEdit?: (client: Client) => void;
  onDelete?: (client: Client) => void;
  isLoading?: boolean;
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}

// Loading skeleton for table rows
function TableSkeleton() {
  return (
    <>
      {[...Array(5)].map((_, i) => (
        <tr key={i} className="animate-pulse">
          <td className="px-4 py-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-full bg-primary-100" />
              <div className="space-y-2">
                <div className="h-4 w-32 bg-primary-100 rounded" />
                <div className="h-3 w-24 bg-primary-100 rounded" />
              </div>
            </div>
          </td>
          <td className="px-4 py-4">
            <div className="h-4 w-40 bg-primary-100 rounded" />
          </td>
          <td className="px-4 py-4">
            <div className="h-4 w-28 bg-primary-100 rounded" />
          </td>
          <td className="px-4 py-4">
            <div className="h-6 w-20 bg-primary-100 rounded-full" />
          </td>
          <td className="px-4 py-4">
            <div className="h-4 w-16 bg-primary-100 rounded" />
          </td>
          <td className="px-4 py-4">
            <div className="flex justify-end gap-2">
              <div className="h-8 w-16 bg-primary-100 rounded" />
              <div className="h-8 w-16 bg-primary-100 rounded" />
            </div>
          </td>
        </tr>
      ))}
    </>
  );
}

export function ClientTable({
  clients,
  onRowClick,
  onEdit,
  onDelete,
  isLoading = false,
  currentPage,
  totalPages,
  onPageChange,
}: ClientTableProps) {
  // Get initials for avatar fallback
  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
  };

  // Get membership badge info
  const getMembershipBadge = (client: Client) => {
    const activeMembership = client.memberships?.[0];
    if (activeMembership && activeMembership.status === "ACTIVE") {
      return {
        label: activeMembership.plan.name,
        className: "bg-accent-100 text-accent-700 border-accent-300",
      };
    }
    return {
      label: "Sin membresia",
      className: "bg-gray-100 text-gray-600 border-gray-200",
    };
  };

  if (isLoading) {
    return (
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-primary-200 bg-primary-50">
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Cliente
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Email
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Telefono
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Membresia
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Reservas
              </th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Acciones
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-primary-100">
            <TableSkeleton />
          </tbody>
        </table>
      </div>
    );
  }

  if (clients.length === 0) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center text-primary-500">
          <svg
            className="w-12 h-12 mx-auto mb-3 text-primary-300"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
            />
          </svg>
          <p className="font-medium">No hay clientes</p>
          <p className="text-sm mt-1">Agrega tu primer cliente para comenzar</p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-primary-200 bg-primary-50">
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Cliente
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Email
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Telefono
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Membresia
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Reservas
              </th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-primary-600 uppercase tracking-wider">
                Acciones
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-primary-100">
            {clients.map((client) => {
              const membershipBadge = getMembershipBadge(client);

              return (
                <tr
                  key={client.id}
                  className="hover:bg-primary-50 transition-colors cursor-pointer"
                  onClick={() => onRowClick?.(client)}
                >
                  {/* Client Name with Avatar */}
                  <td className="px-4 py-4">
                    <div className="flex items-center gap-3">
                      {client.avatar ? (
                        <img
                          src={client.avatar}
                          alt={`${client.firstName} ${client.lastName}`}
                          className="h-10 w-10 rounded-full object-cover"
                        />
                      ) : (
                        <div className="h-10 w-10 rounded-full bg-primary-100 flex items-center justify-center">
                          <span className="text-sm font-medium text-primary-600">
                            {getInitials(client.firstName, client.lastName)}
                          </span>
                        </div>
                      )}
                      <div>
                        <p className="font-medium text-primary-800">
                          {client.firstName} {client.lastName}
                        </p>
                        {client.level && (
                          <p className="text-xs text-primary-500">
                            Nivel: {client.level}
                          </p>
                        )}
                      </div>
                    </div>
                  </td>

                  {/* Email */}
                  <td className="px-4 py-4 text-sm text-primary-600">
                    {client.email || (
                      <span className="text-primary-400">-</span>
                    )}
                  </td>

                  {/* Phone */}
                  <td className="px-4 py-4 text-sm text-primary-600">
                    {client.phone || (
                      <span className="text-primary-400">-</span>
                    )}
                  </td>

                  {/* Membership Status */}
                  <td className="px-4 py-4">
                    <span
                      className={cn(
                        "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border",
                        membershipBadge.className
                      )}
                    >
                      {membershipBadge.label}
                    </span>
                  </td>

                  {/* Bookings Count */}
                  <td className="px-4 py-4 text-sm text-primary-600">
                    {client._count?.bookings || 0}
                  </td>

                  {/* Actions */}
                  <td className="px-4 py-4 text-right">
                    <div
                      className="flex items-center justify-end gap-2"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => onEdit?.(client)}
                      >
                        <svg
                          className="w-4 h-4 mr-1"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                          />
                        </svg>
                        Editar
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => onDelete?.(client)}
                        className="text-red-600 hover:text-red-700 hover:bg-red-50"
                      >
                        <svg
                          className="w-4 h-4"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                          />
                        </svg>
                      </Button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between px-4 py-3 border-t border-primary-200 bg-primary-50">
          <div className="text-sm text-primary-600">
            Pagina {currentPage} de {totalPages}
          </div>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => onPageChange(currentPage - 1)}
              disabled={currentPage <= 1}
            >
              <svg
                className="w-4 h-4 mr-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 19l-7-7 7-7"
                />
              </svg>
              Anterior
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => onPageChange(currentPage + 1)}
              disabled={currentPage >= totalPages}
            >
              Siguiente
              <svg
                className="w-4 h-4 ml-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
