"use client";

import { useState, useCallback } from "react";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";
import { Upload, X, Check, AlertCircle, Loader2 } from "lucide-react";
// File upload config (previously from supabase module, now inlined)
const FILE_UPLOAD_CONFIG = {
  maxFiles: 3,
  maxSizeBytes: 10 * 1024 * 1024, // 10MB
  allowedMimeTypes: [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp",
    "application/pdf",
  ] as const,
  allowedExtensions: [
    ".jpg",
    ".jpeg",
    ".png",
    ".gif",
    ".webp",
    ".pdf",
  ] as const,
};

interface ContactFormProps {
  lang: "ar" | "en";
  translations: any;
}

interface FormData {
  name: string;
  email: string;
  phone: string;
  company: string;
  topic: string;
  message: string;
  preferredLanguage: "ar" | "en";
  consentGiven: boolean;
}

interface FileWithPreview {
  file: File;
  preview?: string;
}

type FormState = "idle" | "uploading" | "submitting" | "success" | "error";

export default function ContactForm({ lang, translations }: ContactFormProps) {
  const { executeRecaptcha } = useGoogleReCaptcha();
  const t = translations.t;
  const isRTL = lang === "ar";

  const [formState, setFormState] = useState<FormState>("idle");
  const [formData, setFormData] = useState<FormData>({
    name: "",
    email: "",
    phone: "",
    company: "",
    topic: "",
    message: "",
    preferredLanguage: lang,
    consentGiven: false,
  });
  const [files, setFiles] = useState<FileWithPreview[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [errorMessage, setErrorMessage] = useState("");
  const [isDragging, setIsDragging] = useState(false);

  // Handle input changes
  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => {
    const { name, value, type } = e.target;
    const checked = (e.target as HTMLInputElement).checked;

    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));

    // Clear error when user starts typing
    if (errors[name]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // Handle file selection
  const handleFileSelect = useCallback(
    (selectedFiles: FileList | null) => {
      if (!selectedFiles || selectedFiles.length === 0) return;

      const newFiles: FileWithPreview[] = [];
      const validationErrors: string[] = [];

      Array.from(selectedFiles).forEach((file) => {
        // Check file count
        if (files.length + newFiles.length >= FILE_UPLOAD_CONFIG.maxFiles) {
          validationErrors.push(t.contactTooManyFiles);
          return;
        }

        // Check file size
        if (file.size > FILE_UPLOAD_CONFIG.maxSizeBytes) {
          validationErrors.push(t.contactFileTooLarge);
          return;
        }

        // Check file type
        if (!FILE_UPLOAD_CONFIG.allowedMimeTypes.includes(file.type as any)) {
          validationErrors.push(t.contactInvalidFileType);
          return;
        }

        // Create preview for images
        let preview: string | undefined;
        if (file.type.startsWith("image/")) {
          preview = URL.createObjectURL(file);
        }

        newFiles.push({ file, preview });
      });

      if (validationErrors.length > 0) {
        setErrorMessage(validationErrors[0]);
        setTimeout(() => setErrorMessage(""), 5000);
        return;
      }

      setFiles((prev) => [...prev, ...newFiles]);
    },
    [files.length, t],
  );

  // Handle file drop
  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);
      handleFileSelect(e.dataTransfer.files);
    },
    [handleFileSelect],
  );

  // Handle file removal
  const handleRemoveFile = (index: number) => {
    setFiles((prev) => {
      const updated = [...prev];
      // Revoke object URL to prevent memory leak
      if (updated[index].preview) {
        URL.revokeObjectURL(updated[index].preview!);
      }
      updated.splice(index, 1);
      return updated;
    });
  };

  // Validate form
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name || formData.name.trim().length < 2) {
      newErrors.name = t.contactNameRequired;
    }
    if (!formData.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = t.contactEmailInvalid;
    }
    if (!formData.phone || formData.phone.trim().length < 8) {
      newErrors.phone = t.contactPhoneRequired;
    }
    if (!formData.topic) {
      newErrors.topic = t.contactTopicRequired;
    }
    if (!formData.message || formData.message.trim().length < 10) {
      newErrors.message = t.contactMessageMinLength;
    }
    if (!formData.consentGiven) {
      newErrors.consent = t.contactConsentRequired;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage("");

    // Validate form
    if (!validateForm()) {
      return;
    }

    // Execute reCAPTCHA
    if (!executeRecaptcha) {
      setErrorMessage(t.contactRecaptchaFailed);
      return;
    }

    try {
      setFormState("submitting");

      const recaptchaToken = await executeRecaptcha("contact_form");

      // Prepare form data
      const submitData = new FormData();
      submitData.append("name", formData.name);
      submitData.append("email", formData.email);
      submitData.append("phone", formData.phone);
      if (formData.company) submitData.append("company", formData.company);
      submitData.append("topic", formData.topic);
      submitData.append("message", formData.message);
      submitData.append("preferredLanguage", formData.preferredLanguage);
      submitData.append("consentGiven", formData.consentGiven.toString());
      submitData.append("recaptchaToken", recaptchaToken);

      // Add files
      files.forEach((fileObj, index) => {
        submitData.append(`file_${index}`, fileObj.file);
      });

      // Submit to API
      const response = await fetch("/api/contact/submit", {
        method: "POST",
        body: submitData,
      });

      const result = await response.json();

      if (!response.ok) {
        if (response.status === 429) {
          setErrorMessage(t.contactRateLimitError);
        } else if (result.errors) {
          const fieldErrors: Record<string, string> = {};
          result.errors.forEach((err: any) => {
            fieldErrors[err.field] = err.message;
          });
          setErrors(fieldErrors);
          setErrorMessage(t.contactErrorMessage);
        } else {
          setErrorMessage(result.error || t.contactServerError);
        }
        setFormState("error");
        return;
      }

      // Success!
      setFormState("success");
    } catch (error) {
      console.error("Form submission error:", error);
      setErrorMessage(t.contactNetworkError);
      setFormState("error");
    }
  };

  // Reset form
  const resetForm = () => {
    setFormData({
      name: "",
      email: "",
      phone: "",
      company: "",
      topic: "",
      message: "",
      preferredLanguage: lang,
      consentGiven: false,
    });
    setFiles([]);
    setErrors({});
    setErrorMessage("");
    setFormState("idle");
  };

  // Success state
  if (formState === "success") {
    return (
      <div className="max-w-2xl mx-auto text-center py-12">
        <div className="w-16 h-16 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-6">
          <Check className="w-8 h-8 text-green-600 dark:text-green-400" />
        </div>
        <h2 className="text-3xl font-bold text-brand-ink dark:text-white mb-4">
          {t.contactSuccessTitle}
        </h2>
        <p className="text-lg text-gray-600 dark:text-gray-300 mb-8">
          {t.contactSuccessMessage}
        </p>
        <button
          onClick={resetForm}
          className="inline-flex items-center px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-green-600 transition-colors"
        >
          {t.contactSuccessButtonText}
        </button>
      </div>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="max-w-2xl mx-auto space-y-6"
      dir={isRTL ? "rtl" : "ltr"}
    >
      {/* Error banner */}
      {errorMessage && (
        <div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-start gap-3">
          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-red-700 dark:text-red-300">
            {errorMessage}
          </p>
        </div>
      )}

      {/* Name field */}
      <div>
        <label
          htmlFor="name"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactNameLabel} <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          placeholder={t.contactNamePlaceholder}
          className={`w-full px-4 py-3 border ${errors.name ? "border-red-500" : "border-gray-300 dark:border-gray-600"} rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white`}
          disabled={formState === "submitting"}
        />
        {errors.name && (
          <p className="mt-1 text-sm text-red-600 dark:text-red-400">
            {errors.name}
          </p>
        )}
      </div>

      {/* Email field */}
      <div>
        <label
          htmlFor="email"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactEmailLabel} <span className="text-red-500">*</span>
        </label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          placeholder={t.contactEmailPlaceholder}
          className={`w-full px-4 py-3 border ${errors.email ? "border-red-500" : "border-gray-300 dark:border-gray-600"} rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white`}
          disabled={formState === "submitting"}
        />
        {errors.email && (
          <p className="mt-1 text-sm text-red-600 dark:text-red-400">
            {errors.email}
          </p>
        )}
      </div>

      {/* Phone field */}
      <div>
        <label
          htmlFor="phone"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactPhoneLabel} <span className="text-red-500">*</span>
        </label>
        <input
          type="tel"
          id="phone"
          name="phone"
          value={formData.phone}
          onChange={handleChange}
          placeholder={t.contactPhonePlaceholder}
          className={`w-full px-4 py-3 border ${errors.phone ? "border-red-500" : "border-gray-300 dark:border-gray-600"} rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white`}
          disabled={formState === "submitting"}
        />
        {errors.phone && (
          <p className="mt-1 text-sm text-red-600 dark:text-red-400">
            {errors.phone}
          </p>
        )}
      </div>

      {/* Company field (optional) */}
      <div>
        <label
          htmlFor="company"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactCompanyLabel}
        </label>
        <input
          type="text"
          id="company"
          name="company"
          value={formData.company}
          onChange={handleChange}
          placeholder={t.contactCompanyPlaceholder}
          className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white"
          disabled={formState === "submitting"}
        />
      </div>

      {/* Topic dropdown */}
      <div>
        <label
          htmlFor="topic"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactTopicLabel} <span className="text-red-500">*</span>
        </label>
        <select
          id="topic"
          name="topic"
          value={formData.topic}
          onChange={handleChange}
          className={`w-full px-4 py-3 border ${errors.topic ? "border-red-500" : "border-gray-300 dark:border-gray-600"} rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white`}
          disabled={formState === "submitting"}
        >
          <option value="">{t.contactTopicPlaceholder}</option>
          <option value="general">{t.contactTopicGeneral}</option>
          <option value="demo">{t.contactTopicDemo}</option>
          <option value="support">{t.contactTopicSupport}</option>
          <option value="sales">{t.contactTopicSales}</option>
          <option value="partnership">{t.contactTopicPartnership}</option>
          <option value="other">{t.contactTopicOther}</option>
        </select>
        {errors.topic && (
          <p className="mt-1 text-sm text-red-600 dark:text-red-400">
            {errors.topic}
          </p>
        )}
      </div>

      {/* Message textarea */}
      <div>
        <label
          htmlFor="message"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactMessageLabel} <span className="text-red-500">*</span>
        </label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          placeholder={t.contactMessagePlaceholder}
          rows={6}
          className={`w-full px-4 py-3 border ${errors.message ? "border-red-500" : "border-gray-300 dark:border-gray-600"} rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white resize-none`}
          disabled={formState === "submitting"}
        />
        {errors.message && (
          <p className="mt-1 text-sm text-red-600 dark:text-red-400">
            {errors.message}
          </p>
        )}
      </div>

      {/* Preferred language */}
      <div>
        <label
          htmlFor="preferredLanguage"
          className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >
          {t.contactPreferredLanguageLabel}{" "}
          <span className="text-red-500">*</span>
        </label>
        <select
          id="preferredLanguage"
          name="preferredLanguage"
          value={formData.preferredLanguage}
          onChange={handleChange}
          className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-gray-800 dark:text-white"
          disabled={formState === "submitting"}
        >
          <option value="ar">{t.contactLanguageArabic}</option>
          <option value="en">{t.contactLanguageEnglish}</option>
        </select>
      </div>

      {/* File upload */}
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
          {t.contactFileUploadLabel}
        </label>
        <div
          className={`border-2 border-dashed ${isDragging ? "border-brand-green bg-green-50 dark:bg-green-900/20" : "border-gray-300 dark:border-gray-600"} rounded-lg p-8 text-center transition-colors`}
          onDragOver={(e) => {
            e.preventDefault();
            setIsDragging(true);
          }}
          onDragLeave={() => setIsDragging(false)}
          onDrop={handleDrop}
        >
          <Upload className="w-8 h-8 mx-auto mb-4 text-gray-400" />
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
            {t.contactDragDropText}
          </p>
          <p className="text-xs text-gray-500 dark:text-gray-500">
            {t.contactFileUploadHint}
          </p>
          <input
            type="file"
            id="file-upload"
            aria-label="Upload files"
            multiple
            accept={FILE_UPLOAD_CONFIG.allowedExtensions.join(",")}
            onChange={(e) => handleFileSelect(e.target.files)}
            className="hidden"
            disabled={
              formState === "submitting" ||
              files.length >= FILE_UPLOAD_CONFIG.maxFiles
            }
          />
          <label
            htmlFor="file-upload"
            className="mt-4 inline-block px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-600 cursor-pointer transition-colors"
          >
            {t.contactFileUploadLabel}
          </label>
        </div>

        {/* File list */}
        {files.length > 0 && (
          <div className="mt-4 space-y-2">
            {files.map((fileObj, index) => (
              <div
                key={index}
                className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg"
              >
                {fileObj.preview && (
                  <img
                    src={fileObj.preview}
                    alt=""
                    className="w-12 h-12 object-cover rounded"
                  />
                )}
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                    {fileObj.file.name}
                  </p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    {(fileObj.file.size / 1024 / 1024).toFixed(2)} MB
                  </p>
                </div>
                <button
                  type="button"
                  aria-label="Remove file"
                  onClick={() => handleRemoveFile(index)}
                  className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                  disabled={formState === "submitting"}
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Consent checkbox */}
      <div>
        <label className="flex items-start gap-3 cursor-pointer">
          <input
            type="checkbox"
            name="consentGiven"
            checked={formData.consentGiven}
            onChange={handleChange}
            className="mt-1 w-4 h-4 text-brand-green border-gray-300 rounded focus:ring-brand-green"
            disabled={formState === "submitting"}
          />
          <span
            className={`text-sm ${errors.consent ? "text-red-600 dark:text-red-400" : "text-gray-700 dark:text-gray-300"}`}
          >
            {t.contactConsentLabel}
          </span>
        </label>
        {errors.consent && (
          <p className="mt-1 text-sm text-red-600 dark:text-red-400">
            {errors.consent}
          </p>
        )}
      </div>

      {/* Submit button */}
      <div>
        <button
          type="submit"
          disabled={formState === "submitting"}
          className="w-full px-6 py-4 bg-brand-green text-white rounded-lg font-semibold hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
        >
          {formState === "submitting" && (
            <Loader2 className="w-5 h-5 animate-spin" />
          )}
          {formState === "submitting"
            ? t.contactSubmittingButton
            : t.contactSubmitButton}
        </button>
      </div>

      {/* reCAPTCHA disclaimer */}
      <p className="text-xs text-center text-gray-500 dark:text-gray-400">
        This site is protected by reCAPTCHA and the Google{" "}
        <a
          href="https://policies.google.com/privacy"
          target="_blank"
          rel="noopener noreferrer"
          className="underline hover:text-brand-green"
        >
          Privacy Policy
        </a>{" "}
        and{" "}
        <a
          href="https://policies.google.com/terms"
          target="_blank"
          rel="noopener noreferrer"
          className="underline hover:text-brand-green"
        >
          Terms of Service
        </a>{" "}
        apply.
      </p>
    </form>
  );
}
