'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Container, Row, Col, Form, Button, Alert, Card, Spinner } from 'react-bootstrap';
import Script from 'next/script';
import { initPayment } from '@/services/adhesionService';
import { motion, AnimatePresence } from 'framer-motion';

type Step = 'form' | 'payment' | 'error';

const COTISATION_AMOUNTS: Record<string, number> = {
  classique: 10,
  soutien: 30,
};

export default function AdhesionPage() {
  const t = useTranslations('Adhesion');
  const [step, setStep] = useState<Step>('form');
  const [token, setToken] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const [type, setType] = useState('particulier');
  const [cotisationType, setCotisationType] = useState('classique');
  const [freeAmount, setFreeAmount] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [address, setAddress] = useState('');
  const [address2, setAddress2] = useState('');
  const [postalCode, setPostalCode] = useState('');
  const [city, setCity] = useState('');
  const [email, setEmail] = useState('');
  const [wantsReceipt, setWantsReceipt] = useState(false);
  const [wantsMemberCard, setWantsMemberCard] = useState(false);
  const [validated, setValidated] = useState(false);

  const amountEuros = cotisationType === 'libre'
    ? (parseFloat(freeAmount) || 0)
    : (COTISATION_AMOUNTS[cotisationType] || 10);

  const amountCents = Math.round(amountEuros * 100);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setValidated(true);

    const form = e.currentTarget;
    if (!form.checkValidity()) return;
    if (amountEuros < 10) return;

    setLoading(true);
    setError('');

    try {
      const result = await initPayment({
        type,
        cotisationType,
        amount: amountCents,
        firstName,
        lastName,
        email,
        address,
        address2: address2 || undefined,
        postalCode,
        city,
        wantsReceipt,
        wantsMemberCard,
      });

      if (result.success && result.token) {
        setToken(result.token);
        setStep('payment');
      } else {
        setError(result.error || t('error_generic'));
      }
    } catch {
      setError(t('error_generic'));
    } finally {
      setLoading(false);
    }
  };

  if (step === 'payment') {
    return (
      <Container className="py-5">
        <h2 className="mb-4">{t('payment_title')}</h2>
        <Card className="mb-4 p-3">
          <p><strong>{t('payment_summary')}</strong></p>
          <p>{firstName} {lastName} — {amountEuros}€ ({t(`cotisation_${cotisationType}`)})</p>
        </Card>
        <Script src="https://homologation-payment.cdn.payline.com/cdn/scripts/widget-min.js" />
        <link href="https://homologation-payment.cdn.payline.com/cdn/styles/widget-min.css" rel="stylesheet" />
        <div
          id="PaylineWidget"
          data-token={token}
          data-template="column"
          data-embeddedredirectionallowed="false"
        />
      </Container>
    );
  }

  return (
    <section className="tk-adhesion">
    <Container style={{ maxWidth: 720 }}>
      <div className="tk-adhesion__head tk-section-head" data-ghost="Emezelañ">
        <div className="w-100 text-center">
          <h1 className="tk-adhesion__title">{t('page_title')}</h1>
          <p className="tk-adhesion__lead">{t('page_lead')}</p>
        </div>
      </div>

      {error && <Alert variant="danger">{error}</Alert>}

      <Form noValidate validated={validated} onSubmit={handleSubmit}>
        {/* Bloc 1 — Type */}
        <Card className="mb-4 p-3">
          <h5>{t('type_label')}</h5>
          {(['particulier', 'association', 'entreprise'] as const).map((val) => (
            <Form.Check
              key={val}
              type="radio"
              name="type"
              id={`type-${val}`}
              label={t(`type_${val}`)}
              checked={type === val}
              onChange={() => setType(val)}
            />
          ))}
        </Card>

        {/* Bloc 2 — Cotisation */}
        <Card className="mb-4 p-3">
          <h5>{t('cotisation_label')}</h5>
          {(['classique', 'soutien', 'libre'] as const).map((val) => (
            <Form.Check
              key={val}
              type="radio"
              name="cotisationType"
              id={`cotisation-${val}`}
              label={t(`cotisation_${val}`)}
              checked={cotisationType === val}
              onChange={() => setCotisationType(val)}
            />
          ))}

          {cotisationType === 'libre' && (
            <Form.Control
              type="number"
              min={10}
              placeholder={t('amount_placeholder')}
              value={freeAmount}
              onChange={(e) => setFreeAmount(e.target.value)}
              className="mt-2"
              required
              isInvalid={validated && (parseFloat(freeAmount) || 0) < 10}
            />
          )}

          <AnimatePresence>
            {wantsReceipt && amountEuros >= 10 && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                className="mt-3 p-3 bg-light rounded"
              >
                <strong>{t('fiscal_title')}</strong>
                <p className="mb-1">{t('fiscal_donation')} : {amountEuros.toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €</p>
                <p className="mb-1">{t('fiscal_reduction')} : {(amountEuros * 0.66).toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €</p>
                <p className="mb-0">{t('fiscal_real_cost')} : {(amountEuros * 0.34).toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €</p>
              </motion.div>
            )}
          </AnimatePresence>
        </Card>

        {/* Bloc 3 — Infos personnelles */}
        <Card className="mb-4 p-3">
          <h5>{t('info_label')}</h5>
          <Row>
            <Col md={6}>
              <Form.Group className="mb-3">
                <Form.Label htmlFor="firstName">{t('first_name')}</Form.Label>
                <Form.Control id="firstName" required value={firstName} onChange={(e) => setFirstName(e.target.value)} />
              </Form.Group>
            </Col>
            <Col md={6}>
              <Form.Group className="mb-3">
                <Form.Label htmlFor="lastName">{t('last_name')}</Form.Label>
                <Form.Control id="lastName" required value={lastName} onChange={(e) => setLastName(e.target.value)} />
              </Form.Group>
            </Col>
          </Row>
          <Form.Group className="mb-3">
            <Form.Label htmlFor="address">{t('address')}</Form.Label>
            <Form.Control id="address" required value={address} onChange={(e) => setAddress(e.target.value)} />
          </Form.Group>
          <Form.Group className="mb-3">
            <Form.Label htmlFor="address2">{t('address2')}</Form.Label>
            <Form.Control id="address2" value={address2} onChange={(e) => setAddress2(e.target.value)} />
          </Form.Group>
          <Row>
            <Col md={4}>
              <Form.Group className="mb-3">
                <Form.Label htmlFor="postalCode">{t('postal_code')}</Form.Label>
                <Form.Control id="postalCode" required pattern="\d{5}" value={postalCode} onChange={(e) => setPostalCode(e.target.value)} />
              </Form.Group>
            </Col>
            <Col md={8}>
              <Form.Group className="mb-3">
                <Form.Label htmlFor="city">{t('city')}</Form.Label>
                <Form.Control id="city" required value={city} onChange={(e) => setCity(e.target.value)} />
              </Form.Group>
            </Col>
          </Row>
          <Form.Group className="mb-3">
            <Form.Label htmlFor="email">{t('email')}</Form.Label>
            <Form.Control id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
          </Form.Group>
        </Card>

        {/* Bloc 4 — Options */}
        <Card className="mb-4 p-3">
          <h5>{t('options_label')}</h5>
          <Form.Check
            type="checkbox"
            id="wantsReceipt"
            label={t('wants_receipt')}
            checked={wantsReceipt}
            onChange={(e) => setWantsReceipt(e.target.checked)}
          />
          {wantsReceipt && (
            <p className="text-muted small mt-1">{t('receipt_info')}</p>
          )}
          <div className="mt-3">
            <Form.Label>{t('wants_member_card')}</Form.Label>
            <div>
              <Form.Check
                inline
                type="radio"
                name="memberCard"
                id="memberCard-yes"
                label={t('member_card_yes')}
                checked={wantsMemberCard}
                onChange={() => setWantsMemberCard(true)}
              />
              <Form.Check
                inline
                type="radio"
                name="memberCard"
                id="memberCard-no"
                label={t('member_card_no')}
                checked={!wantsMemberCard}
                onChange={() => setWantsMemberCard(false)}
              />
            </div>
          </div>
        </Card>

        <Button
          type="submit"
          size="lg"
          className="w-100"
          disabled={loading}
        >
          {loading ? <Spinner size="sm" /> : `${t('submit_button')} — ${amountEuros}€`}
        </Button>
      </Form>
    </Container>
    </section>
  );
}
