'use client';

import React, { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Input, Textarea, Button } from '@/components/ui';
import { sendContactFormAction } from '@/app/actions/contact';
import { useAnalytics } from '@/components/analytics/useAnalytics';
import { AnalyticsEvents } from '@/components/analytics/analytics-events';

interface RequestQuoteFormProps {
  productName: string;
}

export default function RequestQuoteForm({ productName }: RequestQuoteFormProps) {
  const t = useTranslations('Products.form');
  const { trackEvent } = useAnalytics();
  const [email, setEmail] = useState('');
  const [request, setRequest] = useState('');
  const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle');
  const [hasStarted, setHasStarted] = useState(false);

  const handleFocus = (fieldId: string) => {
    // Initial form start
    if (!hasStarted) {
      setHasStarted(true);
      trackEvent(AnalyticsEvents.FORM_START, {
        form_id: 'quote_request_form',
        form_name: 'Product Quote Inquiry',
        product_name: productName,
      });
    }

    // Field-level transparency
    trackEvent(AnalyticsEvents.FORM_FIELD_FOCUS, {
      form_id: 'quote_request_form',
      field_id: fieldId,
      product_name: productName,
    });
  };

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

    const formData = new FormData();
    formData.append('name', 'Product Inquiry'); // Default name for product inquiries
    formData.append('email', email);
    formData.append('message', request);
    formData.append('productName', productName);

    try {
      const result = await sendContactFormAction(formData);
      if (result.success) {
        trackEvent('contact_form_submission', {
          form_type: 'product_quote',
          product_name: productName,
          email: email,
        });
        setStatus('success');
        setEmail('');
        setRequest('');
      } else {
        trackEvent(AnalyticsEvents.FORM_ERROR, {
          form_id: 'quote_request_form',
          product_name: productName,
          error: result.error || 'submission_failed',
        });
        setStatus('error');
      }
    } catch (error) {
      console.error('Form submission error:', error);
      trackEvent(AnalyticsEvents.FORM_ERROR, {
        form_id: 'quote_request_form',
        product_name: productName,
        error: (error as Error).message || 'unexpected_error',
      });
      setStatus('error');
    }
  };

  if (status === 'success') {
    return (
      <div
        className="bg-accent/5 border border-accent/20 text-primary-dark p-4 rounded-xl text-center animate-fade-in !mt-0 w-full"
        role="alert"
        aria-live="polite"
      >
        <div className="flex justify-center mb-3">
          <div className="w-10 h-10 bg-accent rounded-full flex items-center justify-center shadow-lg shadow-accent/20">
            <svg
              className="w-5 h-5 text-primary-dark"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={3}
                d="M5 13l4 4L19 7"
              />
            </svg>
          </div>
        </div>
        <h3 className="text-base font-extrabold mb-1 tracking-tight !mt-0 text-center w-full">
          {t('successTitle')}
        </h3>
        <p className="text-text-secondary text-xs leading-tight mb-4 !mt-0 text-center w-full">
          {t('successDesc', { productName })}
        </p>
        <button
          onClick={() => setStatus('idle')}
          className="inline-flex items-center text-[9px] font-bold uppercase tracking-[0.2em] text-primary hover:text-accent transition-colors group"
        >
          <span className="border-b-2 border-primary/10 group-hover:border-accent transition-colors pb-1">
            {t('sendAnother')}
          </span>
        </button>
      </div>
    );
  }

  if (status === 'error') {
    return (
      <div
        className="bg-destructive/5 border border-destructive/20 text-destructive p-4 rounded-xl text-center animate-fade-in !mt-0 w-full"
        role="alert"
        aria-live="assertive"
      >
        <div className="flex justify-center mb-3">
          <div className="w-10 h-10 bg-destructive rounded-full flex items-center justify-center shadow-lg shadow-destructive/20">
            <svg
              className="w-5 h-5 text-destructive-foreground"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth="3"
            >
              <circle cx="12" cy="12" r="10" />
              <line x1="15" y1="9" x2="9" y2="15" />
              <line x1="9" y1="9" x2="15" y2="15" />
            </svg>
          </div>
        </div>
        <h3 className="text-base font-extrabold mb-1 tracking-tight !mt-0 text-destructive text-center w-full">
          {t('errorTitle') || 'Submission Failed'}
        </h3>
        <p className="text-destructive/80 text-xs leading-tight mb-4 !mt-0 text-center w-full">
          {t('errorDesc') || 'Something went wrong. Please try again.'}
        </p>
        <Button
          onClick={() => setStatus('idle')}
          variant="destructive"
          size="sm"
          className="w-full"
        >
          {t('tryAgain') || 'Try Again'}
        </Button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-3 !mt-0">
      <div className="space-y-2 !mt-0">
        <div className="space-y-1 !mt-0">
          <Input
            type="email"
            id="quote-email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            onFocus={() => handleFocus('quote-email')}
            placeholder={t('email')}
            className="h-9 text-xs !mt-0"
          />
        </div>

        <div className="space-y-1 !mt-0">
          <Textarea
            id="quote-request"
            required
            rows={3}
            value={request}
            onChange={(e) => setRequest(e.target.value)}
            onFocus={() => handleFocus('quote-request')}
            placeholder={t('message')}
            className="text-xs !mt-0"
          />
        </div>
      </div>

      <div className="space-y-2 !mt-0">
        <Button
          type="submit"
          disabled={status === 'submitting'}
          className="w-full py-2 rounded-lg flex items-center justify-center gap-2 group !mt-0"
        >
          {status === 'submitting' ? (
            <>
              <svg
                className="animate-spin h-3 w-3 text-white"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
              >
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                ></circle>
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                ></path>
              </svg>
              <span className="text-xs">{t('submitting')}</span>
            </>
          ) : (
            <>
              <span className="text-xs">{t('submit')}</span>
              <svg
                className="w-3 h-3 transition-transform group-hover:translate-x-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M17 8l4 4m0 0l-4 4m4-4H3"
                />
              </svg>
            </>
          )}
        </Button>

        <p className="text-[7px] text-center text-text-secondary/40 uppercase tracking-[0.15em] font-medium px-2 !mt-1 !mb-0">
          {t('privacyNote')}
        </p>
      </div>
    </form>
  );
}
