"use client";

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

interface PlanFormData {
  name: string;
  description: string;
  price: number;
  durationMonths: number;
  freeHours: number;
  bookingDiscount: number;
  storeDiscount: number;
  extraBenefits: string;
}

interface MembershipPlan {
  id: string;
  name: string;
  description: string | null;
  price: number | string;
  durationMonths: number;
  courtHours: number | null;
  discountPercent: number | string | null;
  benefits: string[] | null;
  benefitsSummary?: {
    freeHours: number;
    bookingDiscount: number;
    extraBenefits: string[];
  };
}

interface PlanFormProps {
  initialData?: MembershipPlan;
  onSubmit: (data: PlanFormData) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
  mode?: "create" | "edit";
}

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

export function PlanForm({
  initialData,
  onSubmit,
  onCancel,
  isLoading = false,
  mode = "create",
}: PlanFormProps) {
  // Extract store discount from benefits if present
  const extractStoreDiscount = (benefits: string[] | null): number => {
    if (!benefits) return 0;
    const storeDiscountBenefit = benefits.find(b => b.includes("store discount"));
    if (storeDiscountBenefit) {
      const match = storeDiscountBenefit.match(/(\d+)%/);
      return match ? parseInt(match[1], 10) : 0;
    }
    return 0;
  };

  const getOtherBenefits = (benefits: string[] | null): string => {
    if (!benefits) return "";
    return benefits
      .filter(b => !b.includes("store discount"))
      .join("\n");
  };

  const [formData, setFormData] = useState<PlanFormData>({
    name: initialData?.name || "",
    description: initialData?.description || "",
    price: initialData?.price ? Number(initialData.price) : 0,
    durationMonths: initialData?.durationMonths || 1,
    freeHours: initialData?.benefitsSummary?.freeHours ?? initialData?.courtHours ?? 0,
    bookingDiscount: initialData?.benefitsSummary?.bookingDiscount ??
      (initialData?.discountPercent ? Number(initialData.discountPercent) : 0),
    storeDiscount: extractStoreDiscount(initialData?.benefits || null),
    extraBenefits: getOtherBenefits(initialData?.benefitsSummary?.extraBenefits || initialData?.benefits || null),
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "number" ? parseFloat(value) || 0 : value,
    }));
    // Clear error when field is modified
    if (errors[name]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "El nombre es requerido";
    }
    if (formData.price <= 0) {
      newErrors.price = "El precio debe ser mayor a 0";
    }
    if (formData.bookingDiscount < 0 || formData.bookingDiscount > 100) {
      newErrors.bookingDiscount = "El descuento debe estar entre 0 y 100";
    }
    if (formData.storeDiscount < 0 || formData.storeDiscount > 100) {
      newErrors.storeDiscount = "El descuento debe estar entre 0 y 100";
    }
    if (formData.freeHours < 0) {
      newErrors.freeHours = "Las horas gratis no pueden ser negativas";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    await onSubmit(formData);
  };

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <form onSubmit={handleSubmit}>
        <CardHeader>
          <CardTitle>
            {mode === "create" ? "Nuevo Plan de Membresia" : "Editar Plan"}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Name */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">
              Nombre del Plan *
            </label>
            <Input
              name="name"
              value={formData.name}
              onChange={handleChange}
              placeholder="Ej: Plan Premium"
              className={errors.name ? "border-red-500" : ""}
            />
            {errors.name && (
              <p className="text-red-500 text-xs mt-1">{errors.name}</p>
            )}
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">
              Descripcion
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleChange}
              placeholder="Descripcion del plan..."
              rows={2}
              className="flex w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-primary-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
            />
          </div>

          {/* Price and Duration */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Precio *
              </label>
              <Input
                type="number"
                name="price"
                value={formData.price}
                onChange={handleChange}
                min={0}
                step={50}
                className={errors.price ? "border-red-500" : ""}
              />
              {errors.price && (
                <p className="text-red-500 text-xs mt-1">{errors.price}</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Duracion
              </label>
              <select
                name="durationMonths"
                value={formData.durationMonths}
                onChange={handleChange}
                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>

          {/* Benefits Section */}
          <div className="border-t border-primary-200 pt-4 mt-4">
            <h4 className="text-sm font-semibold text-primary-800 mb-3">Beneficios</h4>

            {/* Free Hours */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Horas Gratis de Cancha (por mes)
              </label>
              <Input
                type="number"
                name="freeHours"
                value={formData.freeHours}
                onChange={handleChange}
                min={0}
                max={100}
                className={errors.freeHours ? "border-red-500" : ""}
              />
              {errors.freeHours && (
                <p className="text-red-500 text-xs mt-1">{errors.freeHours}</p>
              )}
            </div>

            {/* Discounts */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-sm font-medium text-primary-700 mb-1">
                  Descuento en Reservas (%)
                </label>
                <Input
                  type="number"
                  name="bookingDiscount"
                  value={formData.bookingDiscount}
                  onChange={handleChange}
                  min={0}
                  max={100}
                  className={errors.bookingDiscount ? "border-red-500" : ""}
                />
                {errors.bookingDiscount && (
                  <p className="text-red-500 text-xs mt-1">{errors.bookingDiscount}</p>
                )}
              </div>
              <div>
                <label className="block text-sm font-medium text-primary-700 mb-1">
                  Descuento en Tienda (%)
                </label>
                <Input
                  type="number"
                  name="storeDiscount"
                  value={formData.storeDiscount}
                  onChange={handleChange}
                  min={0}
                  max={100}
                  className={errors.storeDiscount ? "border-red-500" : ""}
                />
                {errors.storeDiscount && (
                  <p className="text-red-500 text-xs mt-1">{errors.storeDiscount}</p>
                )}
              </div>
            </div>

            {/* Extra Benefits */}
            <div>
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Beneficios Adicionales
              </label>
              <textarea
                name="extraBenefits"
                value={formData.extraBenefits}
                onChange={handleChange}
                placeholder="Un beneficio por linea&#10;Ej: Acceso a vestidores VIP&#10;Invitacion a eventos exclusivos"
                rows={4}
                className="flex w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-primary-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
              />
              <p className="text-xs text-primary-500 mt-1">
                Escribe un beneficio por linea
              </p>
            </div>
          </div>
        </CardContent>
        <CardFooter className="flex justify-end gap-3 border-t border-primary-200 bg-primary-50 pt-4">
          <Button type="button" variant="outline" onClick={onCancel}>
            Cancelar
          </Button>
          <Button type="submit" disabled={isLoading}>
            {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" />
                Guardando...
              </span>
            ) : mode === "create" ? (
              "Crear Plan"
            ) : (
              "Guardar Cambios"
            )}
          </Button>
        </CardFooter>
      </form>
    </Card>
  );
}
