import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowRight, MessageCircleQuestion } from "lucide-react";
import { Button } from "@/components/ui/button";

const MAX_QUESTION_LENGTH = 500;

const QuestionBox = () => {
  const [question, setQuestion] = useState("");
  const [error, setError] = useState("");
  const navigate = useNavigate();

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = question.trim();
    if (!trimmed) {
      setError("Please enter your question before submitting.");
      return;
    }
    if (trimmed.length > MAX_QUESTION_LENGTH) {
      setError(`Question must be under ${MAX_QUESTION_LENGTH} characters.`);
      return;
    }
    setError("");
    navigate(`/contact?question=${encodeURIComponent(trimmed)}`);
  };

  return (
    <div className="rounded-2xl border border-border bg-card p-8 max-w-2xl mx-auto">
      <div className="flex items-center gap-3 mb-2">
        <div className="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
          <MessageCircleQuestion className="w-5 h-5 text-primary" />
        </div>
        <h3 className="font-display font-bold text-lg text-foreground">
          Have a specific question?
        </h3>
      </div>
      <p className="text-sm text-muted-foreground mb-5 pl-12">
        Type it below and we'll take you to our contact form with it pre-filled.
      </p>

      <form onSubmit={handleSubmit} className="space-y-3" noValidate>
        <div className="relative">
          <textarea
            placeholder="e.g. Can ChatSKU sync with my existing ERP system?"
            value={question}
            onChange={(e) => {
              setQuestion(e.target.value);
              if (error) setError("");
            }}
            maxLength={MAX_QUESTION_LENGTH}
            rows={3}
            className="w-full rounded-xl border border-border bg-secondary px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary resize-none transition-colors"
            aria-label="Your question"
          />
          <span className="absolute bottom-2.5 right-3 text-xs text-muted-foreground pointer-events-none">
            {question.length}/{MAX_QUESTION_LENGTH}
          </span>
        </div>

        {error && (
          <p className="text-xs text-destructive">{error}</p>
        )}

        <Button
          type="submit"
          className="w-full bg-primary text-primary-foreground hover:bg-primary/90 font-semibold glow-teal-sm"
        >
          Send My Question <ArrowRight className="w-4 h-4" />
        </Button>
      </form>
    </div>
  );
};

export default QuestionBox;
