"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
import { cn, formatCurrency, formatDate } from "@/lib/utils";

interface Client {
  id: string;
  firstName: string;
  lastName: string;
  email: string | null;
  phone: string | null;
}

interface ClientsResponse {
  data: Client[];
  pagination: {
    total: number;
    limit: number;
    offset: number;
    hasMore: boolean;
  };
}

interface MembershipPlan {
  id: string;
  name: string;
  price: number | string;
  durationMonths: number;
  courtHours: number | null;
  discountPercent: number | string | null;
}

interface AssignMembershipDialogProps {
  plans: MembershipPlan[];
  onClose: () => void;
  onAssign: (data: {
    clientId: string;
    planId: string;
    startDate: string;
    endDate: string;
  }) => Promise<void>;
  isLoading?: boolean;
  preselectedClient?: Client;
}

const durationOptions = [
  { value: 1, label: "1 mes" },
  { value: 3, label: "3 meses" },
  { value: 6, label: "6 meses" },
  { value: 12, label: "12 meses" },
];

export function AssignMembershipDialog({
  plans,
  onClose,
  onAssign,
  isLoading = false,
  preselectedClient,
}: AssignMembershipDialogProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [clients, setClients] = useState<Client[]>([]);
  const [selectedClient, setSelectedClient] = useState<Client | null>(preselectedClient || null);
  const [loadingClients, setLoadingClients] = useState(false);
  const [selectedPlanId, setSelectedPlanId] = useState<string>(plans[0]?.id || "");
  const [startDate, setStartDate] = useState<string>(() => {
    const today = new Date();
    return today.toISOString().split("T")[0];
  });
  const [duration, setDuration] = useState<number>(1);
  const [endDate, setEndDate] = useState<string>("");
  const [error, setError] = useState<string | null>(null);

  // Calculate end date based on start date and duration
  useEffect(() => {
    if (startDate && duration) {
      const start = new Date(startDate);
      start.setMonth(start.getMonth() + duration);
      setEndDate(start.toISOString().split("T")[0]);
    }
  }, [startDate, duration]);

  // Fetch clients based on search
  const fetchClients = useCallback(async (search: string) => {
    if (!search || search.trim().length < 2) {
      setClients([]);
      return;
    }

    setLoadingClients(true);
    try {
      const response = await fetch(
        `/api/clients?search=${encodeURIComponent(search)}&limit=10`
      );
      if (!response.ok) {
        throw new Error("Error al buscar clientes");
      }
      const data: ClientsResponse = await response.json();
      setClients(data.data);
    } catch (err) {
      console.error("Error fetching clients:", err);
      setClients([]);
    } finally {
      setLoadingClients(false);
    }
  }, []);

  // Debounce client search
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchClients(searchQuery);
    }, 300);

    return () => clearTimeout(timer);
  }, [searchQuery, fetchClients]);

  // Get selected plan details
  const selectedPlan = plans.find(p => p.id === selectedPlanId);

  const handleSubmit = async () => {
    if (!selectedClient) {
      setError("Selecciona un cliente");
      return;
    }
    if (!selectedPlanId) {
      setError("Selecciona un plan");
      return;
    }
    if (!startDate || !endDate) {
      setError("Selecciona las fechas");
      return;
    }

    setError(null);
    await onAssign({
      clientId: selectedClient.id,
      planId: selectedPlanId,
      startDate: new Date(startDate).toISOString(),
      endDate: new Date(endDate).toISOString(),
    });
  };

  // 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-lg max-h-[90vh] overflow-hidden flex flex-col my-8">
        <CardHeader className="pb-4">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">Asignar Membresia</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="flex-1 overflow-y-auto space-y-4">
          {error && (
            <div className="rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
              {error}
            </div>
          )}

          {/* Client Selection */}
          {!preselectedClient && (
            <div className="space-y-2">
              <label className="block text-sm font-medium text-primary-700">
                Buscar Cliente *
              </label>
              <Input
                type="text"
                placeholder="Nombre, email o telefono..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                autoFocus
              />

              {/* Client search results */}
              <div className="space-y-2 max-h-40 overflow-y-auto">
                {loadingClients && (
                  <div className="flex items-center justify-center py-4">
                    <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary-200 border-t-primary-600" />
                  </div>
                )}

                {!loadingClients && searchQuery.length >= 2 && clients.length === 0 && (
                  <p className="text-sm text-primary-500 text-center py-4">
                    No se encontraron clientes.
                  </p>
                )}

                {!loadingClients &&
                  clients.map((client) => (
                    <button
                      key={client.id}
                      type="button"
                      onClick={() => setSelectedClient(client)}
                      className={cn(
                        "w-full rounded-md border p-3 text-left transition-all",
                        "hover:border-primary-400 hover:bg-primary-50",
                        selectedClient?.id === client.id
                          ? "border-primary-500 bg-primary-50 ring-2 ring-primary-500"
                          : "border-primary-200 bg-white"
                      )}
                    >
                      <p className="font-medium text-primary-800">
                        {client.firstName} {client.lastName}
                      </p>
                      <p className="text-xs text-primary-500">
                        {client.email || client.phone || "Sin contacto"}
                      </p>
                    </button>
                  ))}
              </div>
            </div>
          )}

          {/* Selected client summary */}
          {selectedClient && (
            <div className="rounded-md border border-accent-200 bg-accent-50 p-3">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-accent-600">Cliente seleccionado:</p>
                  <p className="font-medium text-accent-800">
                    {selectedClient.firstName} {selectedClient.lastName}
                  </p>
                </div>
                {!preselectedClient && (
                  <button
                    onClick={() => setSelectedClient(null)}
                    className="text-accent-500 hover:text-accent-700"
                  >
                    <svg className="w-4 h-4" 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>
            </div>
          )}

          {/* Plan Selection */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-2">
              Plan de Membresia *
            </label>
            <select
              value={selectedPlanId}
              onChange={(e) => setSelectedPlanId(e.target.value)}
              className="flex h-10 w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
            >
              <option value="">Selecciona un plan</option>
              {plans.map((plan) => (
                <option key={plan.id} value={plan.id}>
                  {plan.name} - {formatCurrency(Number(plan.price))}
                </option>
              ))}
            </select>

            {/* Selected plan details */}
            {selectedPlan && (
              <div className="mt-2 p-3 rounded-md bg-primary-50 border border-primary-100">
                <div className="flex justify-between text-sm">
                  <span className="text-primary-600">Precio:</span>
                  <span className="font-medium text-primary-800">
                    {formatCurrency(Number(selectedPlan.price))}
                  </span>
                </div>
                {selectedPlan.courtHours && (
                  <div className="flex justify-between text-sm mt-1">
                    <span className="text-primary-600">Horas incluidas:</span>
                    <span className="font-medium text-primary-800">
                      {selectedPlan.courtHours}h
                    </span>
                  </div>
                )}
                {selectedPlan.discountPercent && Number(selectedPlan.discountPercent) > 0 && (
                  <div className="flex justify-between text-sm mt-1">
                    <span className="text-primary-600">Descuento:</span>
                    <span className="font-medium text-primary-800">
                      {Number(selectedPlan.discountPercent)}%
                    </span>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Date Selection */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Fecha de Inicio
              </label>
              <Input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                min={new Date().toISOString().split("T")[0]}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Duracion
              </label>
              <select
                value={duration}
                onChange={(e) => setDuration(Number(e.target.value))}
                className="flex h-10 w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
              >
                {durationOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Calculated End Date */}
          {endDate && (
            <div className="rounded-md bg-primary-50 border border-primary-100 p-3">
              <div className="flex items-center gap-2">
                <svg className="w-5 h-5 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <div>
                  <p className="text-xs text-primary-500">La membresia expirara el:</p>
                  <p className="font-medium text-primary-800">{formatDate(endDate)}</p>
                </div>
              </div>
            </div>
          )}
        </CardContent>

        <CardFooter className="border-t border-primary-200 bg-primary-50 pt-4">
          <div className="flex w-full gap-3">
            <Button variant="outline" onClick={onClose} className="flex-1">
              Cancelar
            </Button>
            <Button
              variant="accent"
              onClick={handleSubmit}
              disabled={!selectedClient || !selectedPlanId || isLoading}
              className="flex-1"
            >
              {isLoading ? (
                <span className="flex items-center gap-2">
                  <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                  Asignando...
                </span>
              ) : (
                "Asignar Membresia"
              )}
            </Button>
          </div>
        </CardFooter>
      </Card>
    </div>
  );
}
