import { FormEvent, useState } from 'react';

import { router, usePage } from '@inertiajs/react';

import { EnterpriseRoiCalculator } from '@/Components/billing/EnterpriseRoiCalculator';
import { Button } from '@/Components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Textarea } from '@/Components/ui/textarea';
import { trackEvent } from '@/lib/analytics';
import {
  ENTERPRISE_CONTACT_SUBMITTED,
  ENTERPRISE_TEAM_FALLBACK_CLICKED,
} from '@/lib/event-catalog';
import type { PageProps } from '@/types';
interface EnterpriseContactModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  pricePerSeat?: number;
  annualPricePerSeat?: number;
}

export function EnterpriseContactModal({
  open,
  onOpenChange,
  pricePerSeat = 199,
  annualPricePerSeat,
}: EnterpriseContactModalProps) {
  const { features } = usePage<PageProps>().props;
  const [form, setForm] = useState({
    name: '',
    email: '',
    company: '',
    site_count: '',
    message: '',
  });
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setErrors({});

    router.post(
      route('contact-sales'),
      {
        name: form.name,
        email: form.email,
        company: form.company,
        site_count: form.site_count ? parseInt(form.site_count, 10) : undefined,
        message: form.message,
      },
      {
        onSuccess: () => {
          trackEvent(ENTERPRISE_CONTACT_SUBMITTED, { company: form.company });
          setSubmitted(true);
          setForm({ name: '', email: '', company: '', site_count: '', message: '' });
        },
        onError: (errs) => {
          setErrors(errs as Record<string, string>);
        },
        onFinish: () => setSubmitting(false),
      },
    );
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(val) => {
        if (!val) setSubmitted(false);
        onOpenChange(val);
      }}
    >
      <DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Enterprise Plan</DialogTitle>
          <DialogDescription>
            Starting at ${pricePerSeat}/seat/mo. Tell us about your needs and we'll get back to you
            within one business day.
          </DialogDescription>
        </DialogHeader>

        {submitted ? (
          <div className="py-6 text-center space-y-4">
            <p className="text-sm font-medium text-foreground">
              Thanks! We'll be in touch within one business day.
            </p>
            <p className="text-sm text-muted-foreground">
              In the meantime, the Agency plan gives you unlimited sites, white-label reports, and
              team roles — ready to activate right now.
            </p>
            <div className="flex flex-col gap-2 sm:flex-row sm:justify-center">
              {features.billing && (
                <Button
                  onClick={() => {
                    trackEvent(ENTERPRISE_TEAM_FALLBACK_CLICKED, { source: 'enterprise_modal_success' });
                    onOpenChange(false);
                    setSubmitted(false);
                    router.visit(route('billing.plans'));
                  }}
                >
                  Start with Agency while we set up Enterprise
                </Button>
              )}
              <Button
                variant="outline"
                onClick={() => {
                  onOpenChange(false);
                  setSubmitted(false);
                }}
              >
                Close
              </Button>
            </div>
          </div>
        ) : (
          <>
            <EnterpriseRoiCalculator
              pricePerSeat={pricePerSeat}
              annualPricePerSeat={annualPricePerSeat}
            />

            <form onSubmit={handleSubmit} className="space-y-4 mt-2">
          <div className="space-y-1">
            <Label htmlFor="es-name">Name</Label>
            <Input
              id="es-name"
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              required
            />
            {errors.name && <p className="text-xs text-destructive">{errors.name}</p>}
          </div>

          <div className="space-y-1">
            <Label htmlFor="es-email">Work Email</Label>
            <Input
              id="es-email"
              type="email"
              value={form.email}
              onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
              required
            />
            {errors.email && <p className="text-xs text-destructive">{errors.email}</p>}
          </div>

          <div className="space-y-1">
            <Label htmlFor="es-company">Company</Label>
            <Input
              id="es-company"
              value={form.company}
              onChange={(e) => setForm((f) => ({ ...f, company: e.target.value }))}
              required
            />
            {errors.company && <p className="text-xs text-destructive">{errors.company}</p>}
          </div>

          <div className="space-y-1">
            <Label htmlFor="es-sites">How many sites? (optional)</Label>
            <Input
              id="es-sites"
              type="number"
              min="1"
              value={form.site_count}
              onChange={(e) => setForm((f) => ({ ...f, site_count: e.target.value }))}
            />
            {errors.site_count && <p className="text-xs text-destructive">{errors.site_count}</p>}
          </div>

          <div className="space-y-1">
            <Label htmlFor="es-message">Message</Label>
            <Textarea
              id="es-message"
              rows={4}
              value={form.message}
              onChange={(e) => setForm((f) => ({ ...f, message: e.target.value }))}
              required
            />
            {errors.message && <p className="text-xs text-destructive">{errors.message}</p>}
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={submitting}>
              {submitting ? 'Sending…' : 'Send Message'}
            </Button>
          </div>
        </form>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}
