"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 month" },
  { value: 3, label: "3 months" },
  { value: 6, label: "6 months" },
  { value: 12, label: "12 months" },
];

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 = "Name is required";
    }
    if (formData.price <= 0) {
      newErrors.price = "Price must be greater than 0";
    }
    if (formData.bookingDiscount < 0 || formData.bookingDiscount > 100) {
      newErrors.bookingDiscount = "Discount must be between 0 and 100";
    }
    if (formData.storeDiscount < 0 || formData.storeDiscount > 100) {
      newErrors.storeDiscount = "Discount must be between 0 and 100";
    }
    if (formData.freeHours < 0) {
      newErrors.freeHours = "Free hours cannot be negative";
    }

    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" ? "New Membership Plan" : "Edit Plan"}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Name */}
          <div>
            <label className="block text-sm font-medium text-primary-700 mb-1">
              Plan Name *
            </label>
            <Input
              name="name"
              value={formData.name}
              onChange={handleChange}
              placeholder="E.g.: Premium Plan"
              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">
              Description
            </label>
            <textarea
              name="description"
              value={formData.description}
              onChange={handleChange}
              placeholder="Plan description..."
              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">
                Price *
              </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">
                Duration
              </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">Benefits</h4>

            {/* Free Hours */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-primary-700 mb-1">
                Free Court Hours (per month)
              </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">
                  Booking Discount (%)
                </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">
                  Store Discount (%)
                </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">
                Additional Benefits
              </label>
              <textarea
                name="extraBenefits"
                value={formData.extraBenefits}
                onChange={handleChange}
                placeholder="One benefit per line&#10;E.g.: Access to VIP locker rooms&#10;Invitation to exclusive events"
                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">
                Write one benefit per line
              </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}>
            Cancel
          </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" />
                Saving...
              </span>
            ) : mode === "create" ? (
              "Create Plan"
            ) : (
              "Save Changes"
            )}
          </Button>
        </CardFooter>
      </form>
    </Card>
  );
}
