'use client';

import { useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { z } from 'zod';
import { motion } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { LabeledInput as Input } from '@/components/ui/labeled-input';
import { LabeledTextarea as Textarea } from '@/components/ui/labeled-textarea';
import { Toast } from '@/components/ui/toast';
import {
  Mail,
  MapPin,
  Send,
  Loader2,
  Clock,
  HeadphonesIcon,
  CheckCircle2,
  HelpCircle,
  ArrowRight,
} from 'lucide-react';
import { trackContactForm, trackConversion } from '@/lib/analytics';
import { BreadcrumbSchema } from '@/components/seo/structured-data';
import { LegacyTooltip as Tooltip } from '@/components/ui/tooltip';

const EASE_OUT = [0.22, 1, 0.36, 1] as const;

const contactFormSchema = z.object({
  name: z.string().min(2, '姓名至少需要2个字符'),
  phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号码'),
  email: z.string().email('请输入有效的邮箱地址'),
  subject: z.string().min(2, '主题至少需要2个字符'),
  message: z.string().min(10, '留言内容至少需要10个字符'),
});

type ContactFormData = z.infer<typeof contactFormSchema>;

interface FormErrors {
  name?: string;
  phone?: string;
  email?: string;
  subject?: string;
  message?: string;
}

interface ContactData {
  heroSubtitle?: string;
  heroTitle?: string;
  heroDescription?: string;
  contactTitle?: string;
  emailLabel?: string;
  addressLabel?: string;
  email?: string;
  address?: string;
  workHoursTitle?: string;
  dayLabel?: string;
  hours?: string;
  commitmentTitle?: string;
  commitmentItems?: string[];
  formTitle?: string;
  successTitle?: string;
  successMessage?: string;
  submitLabel?: string;
  submittingLabel?: string;
  ctaSubtitle?: string;
  ctaTitle?: string;
  ctaDescription?: string;
  ctaPrimaryLabel?: string;
  ctaPrimaryHref?: string;
  ctaSecondaryLabel?: string;
  ctaSecondaryHref?: string;
}

function ContactFormContent({ data }: { data: ContactData }) {
  const searchParams = useSearchParams();
  const isSuccessFromRedirect = searchParams.get('success') === 'true';
  const [showToast, setShowToast] = useState(isSuccessFromRedirect);
  const [toastMessage, setToastMessage] = useState(
    isSuccessFromRedirect ? '表单提交成功！我们会尽快与您联系。' : ''
  );
  const [toastType, setToastType] = useState<'success' | 'error'>(
    isSuccessFromRedirect ? 'success' : 'success'
  );
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(isSuccessFromRedirect);
  const [formData, setFormData] = useState<ContactFormData>({
    name: '',
    phone: '',
    email: '',
    subject: '',
    message: '',
  });
  const [errors, setErrors] = useState<FormErrors>({});

  const emailAddress = data.email ?? '';
  const addressText = data.address ?? '';

  const validateField = (field: keyof ContactFormData, value: string) => {
    try {
      contactFormSchema.shape[field].parse(value);
      setErrors((prev) => ({ ...prev, [field]: undefined }));
    } catch (error) {
      if (error instanceof z.ZodError) {
        const fieldError = error.issues[0];
        if (fieldError) {
          setErrors((prev) => ({ ...prev, [field]: fieldError.message }));
        }
      }
    }
  };

  const handleChange = (field: keyof ContactFormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      validateField(field, value);
    }
  };

  const handleBlur = (field: keyof ContactFormData, value: string) => {
    validateField(field, value);
  };

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const result = contactFormSchema.safeParse(formData);

    if (!result.success) {
      const fieldErrors: FormErrors = {};
      result.error.issues.forEach((issue) => {
        const field = issue.path[0] as keyof ContactFormData;
        if (!fieldErrors[field]) {
          fieldErrors[field] = issue.message;
        }
      });
      setErrors(fieldErrors);
      setToastMessage(`请检查表单：${Object.keys(fieldErrors).length} 项内容需要修正`);
      setToastType('error');
      setShowToast(true);

      // 滚动到表单区域，让用户看到错误提示
      setTimeout(() => {
        const formSection = document.getElementById('contact-form-section');
        if (formSection) {
          formSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
      }, 100);
      return;
    }

    setIsSubmitting(true);

    try {
      const formBody = new URLSearchParams();
      formBody.append('name', formData.name);
      formBody.append('phone', formData.phone);
      formBody.append('email', formData.email);
      formBody.append('subject', formData.subject);
      formBody.append('message', formData.message);

      const response = await fetch('/api/contact', {
        method: 'POST',
        body: formBody,
      });

      const resultData = await response.json();

      if (response.ok && (resultData.success === 'true' || resultData.success === true)) {
        trackContactForm({
          name: formData.name,
          email: formData.email,
          company: formData.subject,
        });
        trackConversion('contact_form_submission');
        setToastMessage(data.successMessage || '');
        setToastType('success');
        setShowToast(true);
        setIsSubmitted(true);
        setFormData({ name: '', phone: '', email: '', subject: '', message: '' });
        setErrors({});
      } else {
        const errorMsg = resultData.message || '提交失败，请稍后重试或直接发送邮件联系我们。';
        if (errorMsg.includes('HTML files') || errorMsg.includes('web server')) {
          setToastMessage(`表单服务需要在生产环境激活。部署后首次提交会发送确认邮件到 ${emailAddress}`);
        } else {
          setToastMessage(errorMsg);
        }
        setToastType('error');
        setShowToast(true);
      }
    } catch {
      setToastMessage('网络错误，请稍后重试。');
      setToastType('error');
      setShowToast(true);
    } finally {
      setIsSubmitting(false);
    }
  }

  const heroTitleLines = (data.heroTitle || '').split('\n');
  const commitmentItems = data.commitmentItems ?? [];

  return (
    <div className="min-h-screen bg-white text-ink overflow-x-hidden">
      <BreadcrumbSchema items={[{ name: '首页', href: '/' }, { name: '联系我们', href: '/contact' }]} />
      {showToast && (
        <Toast
          message={toastMessage}
          type={toastType}
          duration={toastType === 'error' ? 0 : undefined}
          onClose={() => setShowToast(false)}
        />
      )}

      {/* Hero Section */}
      <section className="relative min-h-[80vh] flex items-center overflow-hidden bg-white">
        <div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10 relative z-10 w-full py-28 sm:py-36 md:py-44 lg:py-56">
          <div className="max-w-4xl">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.1, ease: EASE_OUT }}
              className="text-sm font-mono tracking-[0.15em] text-text-muted mb-8"
            >
              {data.heroSubtitle || ''}
            </motion.div>

            <motion.h1
              initial={{ opacity: 0, y: 40 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 1, delay: 0.2, ease: EASE_OUT }}
              className="text-4xl sm:text-5xl md:text-6xl lg:text-7xl xl:text-8xl font-black text-ink leading-[0.88] tracking-tightest mb-10 sm:mb-12 md:mb-16"
            >
              {heroTitleLines.map((line, i) => (
                <div key={i} className={`block ${i > 0 ? 'mt-4 sm:mt-6' : ''}`}>
                  {i === 1 ? (
                    <span className="relative inline-block">
                      <span className="relative text-brand font-black">
                        {line}
                        <motion.span
                          className="absolute -bottom-2 left-0 w-full h-[3px] bg-brand"
                          style={{ transformOrigin: 'left' }}
                          initial={{ scaleX: 0 }}
                          animate={{ scaleX: 1 }}
                          transition={{ duration: 0.8, delay: 1.2, ease: EASE_OUT }}
                        />
                      </span>
                    </span>
                  ) : (
                    line
                  )}
                </div>
              ))}
            </motion.h1>

            <motion.p
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, delay: 0.5, ease: EASE_OUT }}
              className="text-lg md:text-xl text-text-secondary max-w-2xl leading-relaxed mb-12 sm:mb-16"
            >
              {data.heroDescription || ''}
            </motion.p>
          </div>
        </div>
      </section>

      {/* Form + Info Section */}
      <section className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden bg-bg-secondary">
        <div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10 relative z-10">
          <div className="grid lg:grid-cols-5 gap-10 lg:gap-14">
            {/* Left: Contact Info */}
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true, margin: '-60px' }}
              transition={{ duration: 0.8, ease: EASE_OUT }}
              className="lg:col-span-2 space-y-8"
            >
              <div>
                <h2 className="text-xl font-bold text-ink mb-8">{data.contactTitle || ''}</h2>
                <div className="space-y-6" data-testid="contact-info">
                  <div className="flex items-start gap-4" data-testid="email-info">
                    <div className="w-12 h-12 border border-border-primary bg-white flex items-center justify-center shrink-0">
                      <Mail className="w-5 h-5 text-text-secondary" />
                    </div>
                    <div>
                      <p className="text-sm text-text-muted mb-1">{data.emailLabel || ''}</p>
                      <a
                        href={`mailto:${emailAddress}`}
                        className="text-ink hover:text-brand transition-colors duration-300"
                        data-testid="email-link"
                      >
                        {emailAddress}
                      </a>
                    </div>
                  </div>

                  <div className="flex items-start gap-4" data-testid="address-info">
                    <div className="w-12 h-12 border border-border-primary bg-white flex items-center justify-center shrink-0">
                      <MapPin className="w-5 h-5 text-text-secondary" />
                    </div>
                    <div>
                      <p className="text-sm text-text-muted mb-1">{data.addressLabel || ''}</p>
                      <p className="text-ink" data-testid="address-text">
                        {addressText}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="relative border border-border-primary bg-white p-8 overflow-hidden">
                <div className="absolute top-0 left-0 bottom-0 w-0.5 bg-brand/60" />
                <div className="flex items-center gap-3 mb-4">
                  <Clock className="w-5 h-5 text-brand" />
                  <h2 className="text-base font-bold text-ink">{data.workHoursTitle || ''}</h2>
                </div>
                <div className="flex justify-between" data-testid="work-hours-row">
                  <span className="text-text-secondary">{data.dayLabel || ''}</span>
                  <span className="text-brand font-medium">{data.hours || ''}</span>
                </div>
              </div>

              <div className="relative border border-border-primary bg-white p-8 overflow-hidden">
                <div className="absolute top-0 left-0 bottom-0 w-0.5 bg-brand/60" />
                <div className="flex items-center gap-3 mb-4">
                  <HeadphonesIcon className="w-5 h-5 text-text-secondary" />
                  <h2 className="text-base font-bold text-ink">{data.commitmentTitle || ''}</h2>
                </div>
                <div className="space-y-4">
                  {commitmentItems.map((item, idx) => (
                    <div key={idx} className="flex items-start gap-3">
                      <div className="w-1 h-1 bg-text-muted rounded-full mt-2.5 shrink-0" />
                      <p className="text-text-secondary">{item}</p>
                    </div>
                  ))}
                </div>
              </div>
            </motion.div>

            {/* Right: Form */}
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true, margin: '-60px' }}
              transition={{ duration: 0.8, delay: 0.1, ease: EASE_OUT }}
              className="lg:col-span-3"
            >
              <div className="relative border border-border-primary bg-white p-6 sm:p-8 lg:p-10 h-full overflow-hidden" id="contact-form-section">
                <div className="absolute top-0 left-0 right-0 h-0.5 bg-brand" />

                <h2 className="text-xl font-bold text-ink mb-8">{data.formTitle || ''}</h2>

                {Object.keys(errors).length > 0 && (
                  <div className="mb-6 p-4 border border-brand/30 bg-brand/5" role="alert">
                    <p className="text-sm font-bold text-brand mb-2">
                      请修正以下 {Object.keys(errors).length} 项内容：
                    </p>
                    <ul className="space-y-1">
                      {Object.entries(errors).map(([field, message]) => (
                        <li key={field} className="text-sm text-text-secondary flex items-start gap-2">
                          <span className="text-brand shrink-0 mt-0.5">&#8226;</span>
                          <span>{message}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {isSubmitted ? (
                  <div className="text-center py-16">
                    <div className="w-20 h-20 bg-brand rounded-full flex items-center justify-center mx-auto mb-6">
                      <CheckCircle2 className="w-10 h-10 text-white" />
                    </div>
                    <h4 className="text-2xl font-bold text-ink mb-3">{data.successTitle || ''}</h4>
                    <p className="text-text-secondary">{data.successMessage || ''}</p>
                  </div>
                ) : (
                  <form onSubmit={handleSubmit} className="space-y-6" noValidate>
                    <input
                      type="text"
                      name="website"
                      style={{ display: 'none' }}
                      tabIndex={-1}
                      autoComplete="off"
                      aria-hidden="true"
                      aria-label="honeypot"
                    />
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      <div className="relative">
                        <Input
                          name="name"
                          data-testid="name-input"
                          label={
                            <span className="flex items-center gap-1.5">
                              姓名
                              <Tooltip content="用于正式沟通和方案报价">
                                <HelpCircle className="w-3.5 h-3.5 text-text-muted hover:text-brand cursor-help" />
                              </Tooltip>
                            </span>
                          }
                          id="name"
                          placeholder="请输入您的姓名"
                          required
                          value={formData.name}
                          onChange={(e) => handleChange('name', e.target.value)}
                          onBlur={(e) => handleBlur('name', e.target.value)}
                          error={errors.name}
                          className="bg-white border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
                        />
                      </div>
                      <div className="relative">
                        <Input
                          name="phone"
                          data-testid="phone-input"
                          label={
                            <span className="flex items-center gap-1.5">
                              电话
                              <Tooltip content="接收项目进度通知和验证码，仅用于业务联系">
                                <HelpCircle className="w-3.5 h-3.5 text-text-muted hover:text-brand cursor-help" />
                              </Tooltip>
                            </span>
                          }
                          id="phone"
                          type="tel"
                          placeholder="请输入11位手机号"
                          required
                          value={formData.phone}
                          onChange={(e) => handleChange('phone', e.target.value)}
                          onBlur={(e) => handleBlur('phone', e.target.value)}
                          error={errors.phone}
                          className="bg-white border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
                        />
                      </div>
                    </div>
                    <Input
                      name="email"
                      data-testid="email-input"
                      label="邮箱"
                      id="email"
                      type="email"
                      placeholder="请输入您的邮箱"
                      required
                      value={formData.email}
                      onChange={(e) => handleChange('email', e.target.value)}
                      onBlur={(e) => handleBlur('email', e.target.value)}
                      error={errors.email}
                      className="bg-white border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
                    />
                    <Input
                      name="subject"
                      data-testid="subject-input"
                      label="主题"
                      id="subject"
                      placeholder="请输入消息主题"
                      required
                      value={formData.subject}
                      onChange={(e) => handleChange('subject', e.target.value)}
                      onBlur={(e) => handleBlur('subject', e.target.value)}
                      error={errors.subject}
                      className="bg-white border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
                    />
                    <Textarea
                      name="message"
                      data-testid="message-input"
                      label="留言内容"
                      id="message"
                      placeholder="请输入您想咨询的内容"
                      rows={5}
                      required
                      value={formData.message}
                      onChange={(e) => handleChange('message', e.target.value)}
                      onBlur={(e) => handleBlur('message', e.target.value)}
                      error={errors.message}
                      className="bg-white border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
                    />
                    <Button
                      type="submit"
                      data-testid="submit-button"
                      size="xl"
                      className="w-full h-14 disabled:opacity-70"
                      disabled={isSubmitting}
                    >
                      {isSubmitting ? (
                        <span className="flex items-center justify-center gap-2">
                          <Loader2 className="h-5 w-5 animate-spin" />
                          <span>{data.submittingLabel || '...'}</span>
                        </span>
                      ) : (
                        <>
                          <span>{data.submitLabel || '发送'}</span>
                          <Send className="h-4 w-4" />
                        </>
                      )}
                    </Button>
                  </form>
                )}
              </div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* CTA Section */}
      <section className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden bg-white">
        <div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10 relative z-10">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.8, ease: EASE_OUT }}
            className="max-w-3xl mx-auto text-center"
          >
            <div className="text-sm font-mono tracking-[0.2em] text-text-muted uppercase mb-8">
              {data.ctaSubtitle || ''}
            </div>

            <h2 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-black text-ink tracking-tight leading-tight mb-8">
              {data.ctaTitle || ''}
            </h2>

            <p className="text-lg md:text-xl text-text-secondary leading-relaxed mb-12">
              {data.ctaDescription || ''}
            </p>

            <div className="flex flex-col sm:flex-row gap-4 sm:gap-6 justify-center">
              <a
                href={data.ctaPrimaryHref || '#'}
                className="group inline-flex items-center justify-center gap-3 px-12 py-6 font-bold text-base bg-brand text-white transition-all duration-300 hover:bg-brand/90"
              >
                {data.ctaPrimaryLabel || ''}
                <ArrowRight className="w-5 h-5 transition-transform duration-300 group-hover:translate-x-1" />
              </a>
              <a
                href={data.ctaSecondaryHref || '#'}
                className="inline-flex items-center justify-center gap-3 px-12 py-6 font-bold text-base text-ink border border-border-primary hover:border-border-secondary hover:bg-bg-secondary transition-all duration-300"
              >
                {data.ctaSecondaryLabel || ''}
              </a>
            </div>
          </motion.div>
        </div>
      </section>
    </div>
  );
}

function EmptyState() {
  return (
    <div className="min-h-screen bg-white flex items-center justify-center">
      <div className="text-text-muted text-lg">内容暂未发布</div>
    </div>
  );
}

export default function ContactContentV3({ data }: { data: Record<string, unknown> }) {
  const contactData = data as ContactData;

  // Empty state when no CMS data is available
  if (!data || Object.keys(data).length === 0) {
    return <EmptyState />;
  }

  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-white flex items-center justify-center">
          <div className="animate-pulse text-text-muted">加载中...</div>
        </div>
      }
    >
      <ContactFormContent data={contactData} />
    </Suspense>
  );
}
