"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatCurrency, formatDate, cn } from "@/lib/utils";

interface ClientMembership {
  id: string;
  status: string;
  startDate: string;
  endDate: string;
  remainingHours: number | null;
  plan: {
    id: string;
    name: string;
    price: number | string;
    durationMonths: number;
    courtHours: number | null;
  };
}

interface ClientDetail {
  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?: ClientMembership[];
  _count?: {
    bookings: number;
  };
  stats?: {
    totalBookings: number;
    totalSpent: number;
    balance: number;
  };
}

interface ClientDetailDialogProps {
  client: ClientDetail;
  onClose: () => void;
  onEdit?: () => void;
  onAssignMembership?: () => void;
  onAddBalance?: () => void;
}

export function ClientDetailDialog({
  client,
  onClose,
  onEdit,
  onAssignMembership,
  onAddBalance,
}: ClientDetailDialogProps) {
  // Get initials for avatar fallback
  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
  };

  // Get active membership
  const activeMembership = client.memberships?.find(
    (m) => m.status === "ACTIVE"
  );

  // Calculate hours used if there's an active membership with hours
  const hoursTotal = activeMembership?.plan.courtHours || 0;
  const hoursRemaining = activeMembership?.remainingHours || 0;
  const hoursUsed = hoursTotal - hoursRemaining;

  // Handle click outside to close
  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto"
      onClick={handleOverlayClick}
    >
      <Card className="w-full max-w-2xl my-8">
        <CardHeader className="pb-4">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">Detalle del Cliente</CardTitle>
            <button
              onClick={onClose}
              className="rounded-full p-1 hover:bg-primary-100 transition-colors"
            >
              <svg
                className="h-5 w-5 text-primary-500"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* Profile Section */}
          <div className="flex items-start gap-4">
            {client.avatar ? (
              <img
                src={client.avatar}
                alt={`${client.firstName} ${client.lastName}`}
                className="h-20 w-20 rounded-full object-cover border-4 border-primary-100"
              />
            ) : (
              <div className="h-20 w-20 rounded-full bg-primary-100 flex items-center justify-center border-4 border-primary-50">
                <span className="text-2xl font-bold text-primary-600">
                  {getInitials(client.firstName, client.lastName)}
                </span>
              </div>
            )}

            <div className="flex-1">
              <div className="flex items-center gap-2">
                <h2 className="text-xl font-bold text-primary-800">
                  {client.firstName} {client.lastName}
                </h2>
                <span
                  className={cn(
                    "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",
                    client.isActive
                      ? "bg-green-100 text-green-700"
                      : "bg-red-100 text-red-700"
                  )}
                >
                  {client.isActive ? "Activo" : "Inactivo"}
                </span>
              </div>

              {client.level && (
                <p className="text-sm text-primary-500 mt-1">
                  Nivel: {client.level}
                </p>
              )}

              <div className="mt-2 space-y-1">
                {client.email && (
                  <div className="flex items-center gap-2 text-sm text-primary-600">
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                      />
                    </svg>
                    {client.email}
                  </div>
                )}
                {client.phone && (
                  <div className="flex items-center gap-2 text-sm text-primary-600">
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"
                      />
                    </svg>
                    {client.phone}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Membership Section */}
          <div className="border border-primary-200 rounded-lg overflow-hidden">
            <div className="bg-primary-50 px-4 py-2 border-b border-primary-200">
              <h3 className="font-semibold text-primary-800">Membresia</h3>
            </div>
            <div className="p-4">
              {activeMembership ? (
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-primary-600">Plan:</span>
                    <span className="font-medium text-primary-800 bg-accent-100 px-2 py-0.5 rounded-full text-sm">
                      {activeMembership.plan.name}
                    </span>
                  </div>

                  <div className="flex items-center justify-between">
                    <span className="text-sm text-primary-600">Precio:</span>
                    <span className="font-medium text-primary-800">
                      {formatCurrency(Number(activeMembership.plan.price))}
                    </span>
                  </div>

                  <div className="flex items-center justify-between">
                    <span className="text-sm text-primary-600">Inicio:</span>
                    <span className="text-primary-800">
                      {formatDate(activeMembership.startDate)}
                    </span>
                  </div>

                  <div className="flex items-center justify-between">
                    <span className="text-sm text-primary-600">Vencimiento:</span>
                    <span className="text-primary-800">
                      {formatDate(activeMembership.endDate)}
                    </span>
                  </div>

                  {hoursTotal > 0 && (
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-sm text-primary-600">
                          Horas usadas:
                        </span>
                        <span className="text-sm font-medium text-primary-800">
                          {hoursUsed} / {hoursTotal}h
                        </span>
                      </div>
                      <div className="w-full h-2 bg-primary-100 rounded-full overflow-hidden">
                        <div
                          className={cn(
                            "h-full rounded-full transition-all",
                            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>
                  )}
                </div>
              ) : (
                <div className="text-center py-4">
                  <svg
                    className="w-8 h-8 mx-auto mb-2 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="text-sm text-primary-500">Sin membresia activa</p>
                  {onAssignMembership && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={onAssignMembership}
                      className="mt-2"
                    >
                      Asignar Membresia
                    </Button>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* Stats Section */}
          <div className="grid grid-cols-3 gap-4">
            <div className="text-center p-4 bg-primary-50 rounded-lg">
              <p className="text-2xl font-bold text-primary-800">
                {client.stats?.totalBookings || client._count?.bookings || 0}
              </p>
              <p className="text-sm text-primary-500">Reservas</p>
            </div>

            <div className="text-center p-4 bg-primary-50 rounded-lg">
              <p className="text-2xl font-bold text-primary-800">
                {formatCurrency(client.stats?.totalSpent || 0)}
              </p>
              <p className="text-sm text-primary-500">Total Gastado</p>
            </div>

            <div className="text-center p-4 bg-primary-50 rounded-lg">
              <p
                className={cn(
                  "text-2xl font-bold",
                  (client.stats?.balance || 0) >= 0
                    ? "text-green-600"
                    : "text-red-600"
                )}
              >
                {formatCurrency(client.stats?.balance || 0)}
              </p>
              <p className="text-sm text-primary-500">Saldo</p>
            </div>
          </div>

          {/* Notes Section */}
          {client.notes && (
            <div className="border border-primary-200 rounded-lg overflow-hidden">
              <div className="bg-primary-50 px-4 py-2 border-b border-primary-200">
                <h3 className="font-semibold text-primary-800">Notas</h3>
              </div>
              <div className="p-4">
                <p className="text-sm text-primary-600 whitespace-pre-wrap">
                  {client.notes}
                </p>
              </div>
            </div>
          )}

          {/* Member Since */}
          <div className="text-center text-sm text-primary-500">
            Cliente desde {formatDate(client.createdAt)}
          </div>

          {/* Action Buttons */}
          <div className="flex gap-3 pt-4 border-t border-primary-200">
            {onEdit && (
              <Button variant="outline" onClick={onEdit} className="flex-1">
                <svg
                  className="w-4 h-4 mr-2"
                  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>
            )}

            {activeMembership && onAssignMembership && (
              <Button
                variant="outline"
                onClick={onAssignMembership}
                className="flex-1"
              >
                <svg
                  className="w-4 h-4 mr-2"
                  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>
            )}

            {!activeMembership && onAssignMembership && (
              <Button
                variant="accent"
                onClick={onAssignMembership}
                className="flex-1"
              >
                <svg
                  className="w-4 h-4 mr-2"
                  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>
                Asignar Membresia
              </Button>
            )}

            {onAddBalance && (
              <Button variant="outline" onClick={onAddBalance} className="flex-1">
                <svg
                  className="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                  />
                </svg>
                Agregar Saldo
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
