"use client";

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

interface Membership {
  id: string;
  startDate: string;
  endDate: string;
  status: "ACTIVE" | "EXPIRED" | "CANCELLED" | "SUSPENDED";
  remainingHours: number | null;
  autoRenew: boolean;
  isExpiring?: boolean;
  daysUntilExpiry?: number | null;
  plan: {
    id: string;
    name: string;
    price: number | string;
    durationMonths: number;
    courtHours: number | null;
  };
  client: {
    id: string;
    firstName: string;
    lastName: string;
    email: string | null;
    phone: string | null;
  };
  benefitsSummary?: {
    freeHours: number;
    hoursRemaining: number;
  };
}

interface MembershipTableProps {
  memberships: Membership[];
  onRenew?: (membership: Membership) => void;
  onCancel?: (membership: Membership) => void;
  onViewDetails?: (membership: Membership) => void;
  isLoading?: boolean;
}

const statusConfig: Record<string, { label: string; className: string }> = {
  ACTIVE: {
    label: "Activa",
    className: "bg-green-100 text-green-700 border-green-300",
  },
  EXPIRED: {
    label: "Expirada",
    className: "bg-red-100 text-red-700 border-red-300",
  },
  CANCELLED: {
    label: "Cancelada",
    className: "bg-gray-100 text-gray-700 border-gray-300",
  },
  SUSPENDED: {
    label: "Suspendida",
    className: "bg-yellow-100 text-yellow-700 border-yellow-300",
  },
};

export function MembershipTable({
  memberships,
  onRenew,
  onCancel,
  onViewDetails,
  isLoading = false,
}: MembershipTableProps) {
  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
          <p className="text-primary-500">Cargando membresias...</p>
        </div>
      </div>
    );
  }

  if (memberships.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="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"
            />
          </svg>
          <p className="font-medium">No hay membresias</p>
          <p className="text-sm mt-1">Asigna una membresia a un cliente para comenzar</p>
        </div>
      </div>
    );
  }

  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">
              Plan
            </th>
            <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
              Inicio
            </th>
            <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
              Fin
            </th>
            <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
              Horas Usadas
            </th>
            <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
              Estado
            </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">
          {memberships.map((membership) => {
            const status = statusConfig[membership.status] || statusConfig.ACTIVE;
            const hoursTotal = membership.plan.courtHours || membership.benefitsSummary?.freeHours || 0;
            const hoursRemaining = membership.remainingHours ?? membership.benefitsSummary?.hoursRemaining ?? 0;
            const hoursUsed = hoursTotal - hoursRemaining;

            return (
              <tr
                key={membership.id}
                className={cn(
                  "hover:bg-primary-50 transition-colors",
                  membership.isExpiring && membership.status === "ACTIVE" && "bg-yellow-50"
                )}
              >
                {/* Client */}
                <td className="px-4 py-4">
                  <div>
                    <p className="font-medium text-primary-800">
                      {membership.client.firstName} {membership.client.lastName}
                    </p>
                    <p className="text-xs text-primary-500">
                      {membership.client.email || membership.client.phone || "Sin contacto"}
                    </p>
                  </div>
                </td>

                {/* Plan */}
                <td className="px-4 py-4">
                  <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary-100 text-primary-700">
                    {membership.plan.name}
                  </span>
                </td>

                {/* Start Date */}
                <td className="px-4 py-4 text-sm text-primary-600">
                  {formatDate(membership.startDate)}
                </td>

                {/* End Date */}
                <td className="px-4 py-4">
                  <div>
                    <p className="text-sm text-primary-600">
                      {formatDate(membership.endDate)}
                    </p>
                    {membership.isExpiring && membership.status === "ACTIVE" && (
                      <p className="text-xs text-yellow-600 font-medium flex items-center gap-1">
                        <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                        </svg>
                        Expira en {membership.daysUntilExpiry} dias
                      </p>
                    )}
                  </div>
                </td>

                {/* Hours Used */}
                <td className="px-4 py-4">
                  {hoursTotal > 0 ? (
                    <div>
                      <p className="text-sm text-primary-700">
                        {hoursUsed} / {hoursTotal}h
                      </p>
                      <div className="mt-1 w-20 h-1.5 bg-primary-100 rounded-full overflow-hidden">
                        <div
                          className={cn(
                            "h-full rounded-full",
                            hoursUsed >= hoursTotal
                              ? "bg-red-500"
                              : hoursUsed >= hoursTotal * 0.75
                              ? "bg-yellow-500"
                              : "bg-accent-500"
                          )}
                          style={{ width: `${Math.min((hoursUsed / hoursTotal) * 100, 100)}%` }}
                        />
                      </div>
                    </div>
                  ) : (
                    <span className="text-sm text-primary-400">-</span>
                  )}
                </td>

                {/* 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",
                      status.className
                    )}
                  >
                    {status.label}
                  </span>
                </td>

                {/* Actions */}
                <td className="px-4 py-4 text-right">
                  <div className="flex items-center justify-end gap-2">
                    {membership.status === "ACTIVE" && (
                      <>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => onRenew?.(membership)}
                          className="text-accent-600 hover:text-accent-700 hover:bg-accent-50"
                        >
                          <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                          </svg>
                          Renovar
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => onCancel?.(membership)}
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          <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="M6 18L18 6M6 6l12 12" />
                          </svg>
                          Cancelar
                        </Button>
                      </>
                    )}
                    {(membership.status === "EXPIRED" || membership.status === "CANCELLED") && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => onRenew?.(membership)}
                        className="text-accent-600 hover:text-accent-700 hover:bg-accent-50"
                      >
                        <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                        Reactivar
                      </Button>
                    )}
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
