'use client';

import React, { useState } from 'react';
import { PricingPlan } from '@/types';

interface PlanDefinitionModalProps {
  plan: PricingPlan | null;
  onClose: () => void;
  onSave: (updatedPlan: Partial<PricingPlan> & { plan_id: string }) => Promise<void>;
}

export default function PlanDefinitionModal({
  plan,
  onClose,
  onSave,
}: PlanDefinitionModalProps) {
  if (!plan) return null;

  const [name, setName] = useState(plan.name || '');
  const [description, setDescription] = useState(plan.description || '');
  const [price, setPrice] = useState(String(plan.price ?? 0));
  const [yearlyPrice, setYearlyPrice] = useState(
    plan.yearly_price != null ? String(plan.yearly_price) : String(Number(plan.price || 0) * 12 * 0.8)
  );
  const [currency, setCurrency] = useState(plan.currency || 'USD');
  const [interval, setInterval] = useState(plan.interval || 'month');
  const [yearlyDiscountLabel, setYearlyDiscountLabel] = useState(plan.yearly_discount_label || 'Save 20%');
  const [displayOrder, setDisplayOrder] = useState(String(plan.display_order ?? 1));
  const [trialDays, setTrialDays] = useState(String(plan.trial_days ?? 0));
  const [skuLimit, setSkuLimit] = useState(plan.sku_limit != null ? String(plan.sku_limit) : '');
  const [campaignsLimit, setCampaignsLimit] = useState(plan.campaigns_limit != null ? String(plan.campaigns_limit) : '');
  const [badge, setBadge] = useState(plan.badge || '');
  const [isActive, setIsActive] = useState(plan.is_active ?? true);
  const [isVisible, setIsVisible] = useState(plan.is_visible ?? true);
  const [featuresText, setFeaturesText] = useState(
    Array.isArray(plan.features) ? plan.features.join('\n') : ''
  );
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    const parsedPrice = parseFloat(price);
    if (isNaN(parsedPrice) || parsedPrice < 0) {
      setError('Please provide a valid monthly price (greater than or equal to 0).');
      return;
    }

    const parsedYearly = parseFloat(yearlyPrice);
    if (isNaN(parsedYearly) || parsedYearly < 0) {
      setError('Please provide a valid yearly price.');
      return;
    }

    const parsedTrial = parseInt(trialDays, 10);
    if (isNaN(parsedTrial) || parsedTrial < 0) {
      setError('Please provide a valid number of trial days (0 for no trial).');
      return;
    }

    const featureList = featuresText
      .split('\n')
      .map((f) => f.trim())
      .filter(Boolean);

    setIsSubmitting(true);
    try {
      await onSave({
        plan_id: plan.id,
        name: name.trim() || plan.name,
        description: description.trim() || null,
        price: parsedPrice,
        yearly_price: parsedYearly,
        currency: currency.trim().toUpperCase() || 'USD',
        interval: interval === 'year' ? 'year' : 'month',
        yearly_discount_label: yearlyDiscountLabel.trim() || 'Save 20%',
        display_order: parseInt(displayOrder, 10) || 1,
        trial_days: parsedTrial,
        sku_limit: skuLimit.trim() === '' ? null : parseInt(skuLimit, 10),
        campaigns_limit: campaignsLimit.trim() === '' ? null : parseInt(campaignsLimit, 10),
        badge: badge.trim() || null,
        is_active: isActive,
        is_visible: isVisible,
        features: featureList,
      });
      onClose();
    } catch (err: any) {
      setError(err?.message || 'Failed to update plan');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl border border-slate-200 shadow-2xl w-full max-w-2xl overflow-hidden animate-in fade-in zoom-in-95 max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="p-5 border-b border-slate-100 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-lg bg-theme/10 text-theme flex items-center justify-center font-bold text-xs">
              <i className="fa-solid fa-pen-to-square" />
            </div>
            <div>
              <h3 className="text-sm font-bold text-slate-900">
                Edit {plan.name}
              </h3>
              <p className="text-[11px] text-slate-400 font-mono">
                Plan ID: {plan.id} &bull; Changes reflect dynamically across SaaS Admin and /pricing
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg text-slate-400 hover:text-slate-600 flex items-center justify-center cursor-pointer"
          >
            ✕
          </button>
        </div>

        {/* Scrollable Form Body */}
        <form onSubmit={handleSubmit} className="p-5 space-y-4 text-xs overflow-y-auto flex-1">
          {error && (
            <div className="p-3 rounded-lg bg-rose-50 border border-rose-200 text-rose-700 font-medium">
              {error}
            </div>
          )}

          {/* Section 1: Plan Details */}
          <div className="space-y-3 border-b border-slate-100 pb-4">
            <h4 className="text-[11px] font-extrabold uppercase tracking-wider text-slate-500">Plan Details</h4>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1">
                <label className="font-bold text-slate-700">Plan Display Name *</label>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="e.g. Growth Plan"
                />
              </div>

              <div className="space-y-1">
                <label className="font-bold text-slate-700">Badge Label (Optional)</label>
                <input
                  type="text"
                  value={badge}
                  onChange={(e) => setBadge(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="e.g. Most Popular or Recommended"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="font-bold text-slate-700">Plan Description</label>
              <input
                type="text"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-medium focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                placeholder="e.g. Unlimited pixels, daily feed sync, and conversions API for growing brands"
              />
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1">
                <label className="font-bold text-slate-700">Display Order (Sorting)</label>
                <input
                  type="number"
                  min="1"
                  value={displayOrder}
                  onChange={(e) => setDisplayOrder(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="1, 2, 3..."
                />
              </div>
              <div className="space-y-1">
                <label className="font-bold text-slate-700">Currency</label>
                <input
                  type="text"
                  value={currency}
                  onChange={(e) => setCurrency(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="USD"
                />
              </div>
            </div>
          </div>

          {/* Section 2: Pricing & Billing */}
          <div className="space-y-3 border-b border-slate-100 pb-4">
            <h4 className="text-[11px] font-extrabold uppercase tracking-wider text-slate-500">Pricing &amp; Billing</h4>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <div className="space-y-1">
                <label className="font-bold text-slate-700">Monthly Price ($)</label>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  value={price}
                  onChange={(e) => setPrice(e.target.value)}
                  required
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="0 for free"
                />
              </div>

              <div className="space-y-1">
                <label className="font-bold text-slate-700">Yearly Price ($)</label>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  value={yearlyPrice}
                  onChange={(e) => setYearlyPrice(e.target.value)}
                  required
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="Annual cost"
                />
              </div>

              <div className="space-y-1">
                <label className="font-bold text-slate-700">Yearly Savings Label</label>
                <input
                  type="text"
                  value={yearlyDiscountLabel}
                  onChange={(e) => setYearlyDiscountLabel(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="Save 20%"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1">
                <label className="font-bold text-slate-700">Trial Period (Days)</label>
                <input
                  type="number"
                  min="0"
                  value={trialDays}
                  onChange={(e) => setTrialDays(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="14"
                />
                <span className="text-[10px] text-slate-400">0 for no free trial</span>
              </div>

              <div className="space-y-1">
                <label className="font-bold text-slate-700">Billing Interval</label>
                <select
                  value={interval}
                  onChange={(e) => setInterval(e.target.value as 'month' | 'year')}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                >
                  <option value="month">Monthly (30 Days)</option>
                  <option value="year">Annual (365 Days)</option>
                </select>
              </div>
            </div>
          </div>

          {/* Section 3: Quotas & Feature Limits */}
          <div className="space-y-3 border-b border-slate-100 pb-4">
            <h4 className="text-[11px] font-extrabold uppercase tracking-wider text-slate-500">Quotas &amp; Feature Limits</h4>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1">
                <label className="font-bold text-slate-700">Catalog SKU Limit</label>
                <input
                  type="number"
                  min="1"
                  value={skuLimit}
                  onChange={(e) => setSkuLimit(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="Leave blank for Unlimited"
                />
                <span className="text-[10px] text-slate-400">Blank = Unlimited products synchronized</span>
              </div>

              <div className="space-y-1">
                <label className="font-bold text-slate-700">Catalog Feeds Quota</label>
                <input
                  type="number"
                  min="1"
                  value={campaignsLimit}
                  onChange={(e) => setCampaignsLimit(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-semibold focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme"
                  placeholder="Leave blank for Unlimited"
                />
                <span className="text-[10px] text-slate-400">1 for Free, 3 for Growth, blank for Scale</span>
              </div>
            </div>
          </div>

          {/* Section 4: Features Included Checklist */}
          <div className="space-y-1 border-b border-slate-100 pb-4">
            <div className="flex items-center justify-between">
              <label className="font-bold text-slate-700">Plan Highlights (One per line)</label>
              <span className="text-[10px] text-slate-400">Card bullet points on /pricing</span>
            </div>
            <textarea
              rows={5}
              value={featuresText}
              onChange={(e) => setFeaturesText(e.target.value)}
              className="w-full px-3 py-2 rounded-lg border border-slate-200 text-slate-800 font-mono text-[11px] focus:outline-none focus:border-theme focus:ring-1 focus:ring-theme leading-relaxed"
              placeholder="Unlimited Meta Pixels&#10;Track Events Using Conversion API&#10;14-Day Free Trial"
            />
          </div>

          {/* Section 5: Status & Visibility */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div className="p-3 rounded-xl border border-slate-200 bg-slate-50/70 flex items-center justify-between">
              <div>
                <span className="font-bold text-slate-800 text-xs block">Active Status</span>
                <span className="text-[10px] text-slate-500">
                  {isActive ? 'Plan can be selected' : 'Plan is deactivated'}
                </span>
              </div>
              <button
                type="button"
                onClick={() => setIsActive(!isActive)}
                className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out ${
                  isActive ? 'bg-emerald-500' : 'bg-slate-300'
                }`}
              >
                <span
                  className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                    isActive ? 'translate-x-5' : 'translate-x-0'
                  }`}
                />
              </button>
            </div>

            <div className="p-3 rounded-xl border border-slate-200 bg-slate-50/70 flex items-center justify-between">
              <div>
                <span className="font-bold text-slate-800 text-xs block">Pricing Page Visibility</span>
                <span className="text-[10px] text-slate-500">
                  {isVisible ? 'Visible to merchants' : 'Hidden from /pricing'}
                </span>
              </div>
              <button
                type="button"
                onClick={() => setIsVisible(!isVisible)}
                className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out ${
                  isVisible ? 'bg-indigo-500' : 'bg-slate-300'
                }`}
              >
                <span
                  className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                    isVisible ? 'translate-x-5' : 'translate-x-0'
                  }`}
                />
              </button>
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center justify-end gap-2 pt-3 border-t border-slate-100">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg text-xs font-semibold bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 cursor-pointer"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 rounded-lg text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-xs flex items-center gap-1.5 transition-colors cursor-pointer"
            >
              {isSubmitting && <i className="fa-solid fa-arrows-rotate fa-spin text-xs" />}
              <span>Save Plan Changes</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
