'use client';

import { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { CreditCard, Lock, AlertTriangle, Loader2 } from 'lucide-react';
import CardSetupForm from './CardSetupModal';
import { useSession } from '../lib/session-context';

interface PaymentGateProps {
  onPaymentMethodAdded: () => void;
}

export default function PaymentGate({ onPaymentMethodAdded }: PaymentGateProps) {
  const { user: sessionUser } = useSession();
  const [checking, setChecking] = useState(true);
  const [hasPaymentMethod, setHasPaymentMethod] = useState(false);
  const [hasRequiredFinancialData, setHasRequiredFinancialData] = useState(false);
  const [showPaymentMethodForm, setShowPaymentMethodForm] = useState(false);
  const [savingFinancial, setSavingFinancial] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [financialForm, setFinancialForm] = useState({
    billingAddress: '',
    billingEmail: '',
    taxId: '',
    vatNumber: '',
  });

  const loadFinancialData = async (companyId: string) => {
    try {
      const res = await fetch(`/api/companies/${companyId}/financial`, { credentials: 'include' });
      if (!res.ok) return;
      const data = await res.json();
      const f = data?.financialData ?? {};
      setFinancialForm({
        billingAddress: f.billingAddress ?? '',
        billingEmail: f.billingEmail ?? '',
        taxId: f.taxId ?? '',
        vatNumber: f.vatNumber ?? '',
      });
    } catch {
      // Best effort; user can still fill manually.
    }
  };

  const checkPaymentStatus = async () => {
    try {
      const res = await fetch('/api/billing/status');
      if (!res.ok) {
        if (res.status === 401) {
          window.location.href = '/';
          return;
        }
        throw new Error('Failed to check payment status');
      }
      const data = await res.json();
      setHasPaymentMethod(data.hasPaymentMethod);
      const financialReady = (data.hasRequiredFinancialData ?? true) === true;
      setHasRequiredFinancialData(financialReady);
      if (!financialReady && sessionUser?.companyId) {
        await loadFinancialData(sessionUser.companyId);
      }
      if ((data.requirementsComplete ?? data.hasPaymentMethod) === true) {
        onPaymentMethodAdded();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error checking payment status');
    } finally {
      setChecking(false);
    }
  };

  useEffect(() => {
    checkPaymentStatus();
  }, [sessionUser?.companyId]);

  const handleSaveFinancialInfo = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!sessionUser?.companyId) {
      setError('Company not found for current owner');
      return;
    }
    if (!financialForm.billingAddress.trim() || !financialForm.billingEmail.trim()) {
      setError('Billing address and billing email are required');
      return;
    }

    setSavingFinancial(true);
    setError(null);
    try {
      const res = await fetch(`/api/companies/${sessionUser.companyId}/financial`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          billingAddress: financialForm.billingAddress.trim(),
          billingEmail: financialForm.billingEmail.trim(),
          taxId: financialForm.taxId.trim() || undefined,
          vatNumber: financialForm.vatNumber.trim() || undefined,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || 'Failed to save financial information');
      }
      setHasRequiredFinancialData(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save financial information');
    } finally {
      setSavingFinancial(false);
    }
  };

  const handleCardSetupSuccess = () => {
    setShowPaymentMethodForm(false);
    setHasPaymentMethod(true);
    onPaymentMethodAdded();
  };

  // If still checking or already has payment method, don't show the gate
  if (checking || hasPaymentMethod) {
    return (
      <div className="fixed inset-0 bg-background flex items-center justify-center z-50">
        <div className="flex flex-col items-center gap-4">
          <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-accent" />
          <p className="text-sm text-muted">Checking account status...</p>
        </div>
      </div>
    );
  }

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 bg-background/95 backdrop-blur-sm flex items-start justify-center z-50 p-4 overflow-y-auto"
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
          className="w-full max-w-4xl my-6"
        >
          <div className="glass rounded-2xl p-8 space-y-6">
            {/* Header */}
            <div className="text-center space-y-3">
              <div className="w-16 h-16 rounded-2xl gradient-accent flex items-center justify-center mx-auto shadow-lg shadow-accent/20">
                <CreditCard className="w-8 h-8 text-white" />
              </div>
              <h2 className="text-2xl font-bold text-foreground">
                Payment Method Required
              </h2>
              <p className="text-sm text-muted max-w-sm mx-auto leading-relaxed">
                To use Scriba, you need to add a payment method. 
                You will only be charged based on your actual token usage at the end of each month.
              </p>
            </div>

            {/* Info Box */}
            <div className="glass-light rounded-xl p-4 space-y-3">
              <div className="flex items-start gap-3">
                <Lock className="w-4 h-4 text-success shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-foreground">Secure & Transparent</p>
                  <p className="text-xs text-muted mt-0.5">
                    Your payment method details are securely stored by Stripe.
                    We never store full payment credentials on our servers.
                  </p>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <AlertTriangle className="w-4 h-4 text-accent-light shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-foreground">Pay-as-you-go</p>
                  <p className="text-xs text-muted mt-0.5">
                    You are only charged for tokens you actually use. 
                    No upfront fees, no minimum commitments.
                  </p>
                </div>
              </div>
            </div>

            {/* Error Message */}
            {error && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                className="flex items-center gap-2 px-4 py-3 rounded-lg bg-danger/10 border border-danger/25 text-danger text-sm"
              >
                <AlertTriangle className="w-4 h-4 shrink-0" />
                {error}
              </motion.div>
            )}

            {/* Financial Info (required before payment method) */}
            {!hasRequiredFinancialData && (
              <form onSubmit={handleSaveFinancialInfo} className="space-y-3 glass-light rounded-xl p-4">
                <p className="text-sm font-medium text-foreground">Financial Information (required)</p>
                <p className="text-xs text-muted">
                  Add billing address and billing email before adding your payment method.
                </p>
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">
                    Billing Address <span className="text-red-400">*</span>
                  </label>
                  <textarea
                    rows={2}
                    required
                    value={financialForm.billingAddress}
                    onChange={(e) => setFinancialForm({ ...financialForm, billingAddress: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition resize-none"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">
                    Billing Email <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="email"
                    required
                    value={financialForm.billingEmail}
                    onChange={(e) => setFinancialForm({ ...financialForm, billingEmail: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition"
                  />
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-muted mb-1.5">Tax ID (optional)</label>
                    <input
                      type="text"
                      value={financialForm.taxId}
                      onChange={(e) => setFinancialForm({ ...financialForm, taxId: e.target.value })}
                      className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-muted mb-1.5">VAT Number (optional)</label>
                    <input
                      type="text"
                      value={financialForm.vatNumber}
                      onChange={(e) => setFinancialForm({ ...financialForm, vatNumber: e.target.value })}
                      className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition"
                    />
                  </div>
                </div>
                <button
                  type="submit"
                  disabled={savingFinancial}
                  className="w-full py-2.5 rounded-xl bg-surface-light border border-border text-foreground font-medium hover:bg-surface transition disabled:opacity-50"
                >
                  {savingFinancial ? 'Saving…' : 'Save Financial Information'}
                </button>
              </form>
            )}

            {/* Card Form or CTA */}
            <AnimatePresence mode="wait">
              {showPaymentMethodForm ? (
                <motion.div
                  key="form"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                >
                  <CardSetupForm
                    onSuccess={handleCardSetupSuccess}
                    onCancel={() => setShowPaymentMethodForm(false)}
                  />
                </motion.div>
              ) : (
                <motion.div
                  key="cta"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="space-y-3"
                >
                  <button
                    onClick={() => setShowPaymentMethodForm(true)}
                    disabled={!hasRequiredFinancialData}
                    className="w-full py-3 rounded-xl gradient-accent text-white font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2"
                  >
                    <CreditCard className="w-4 h-4" />
                    Add Payment Method
                  </button>
                  <p className="text-xs text-muted text-center">
                    {!hasRequiredFinancialData
                      ? 'Complete financial information first, then add your payment method.'
                      : 'You can add card, PayPal, SEPA, and wallets depending on Stripe account settings.'}
                  </p>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
