"use client";

import { useState, useCallback, useEffect } from "react";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";
import { Upload, X, Check, AlertCircle, Loader2 } from "lucide-react";
import type { Lang } from "@/lib/config";
// 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,
};

type Topic =
  | "sales"
  | "support"
  | "billing"
  | "partnerships"
  | "press"
  | "careers"
  | "security";

type LanguageChoice = "ar" | "en";

type FormCopy = {
  nameLabel: string;
  emailLabel: string;
  phoneLabel: string;
  phoneHint: string;
  companyLabel: string;
  topicLabel: string;
  topicPlaceholder: string;
  messageLabel: string;
  messagePlaceholder: string;
  attachmentsLabel: string;
  attachmentsHint: string;
  consentLabel: string;
  languageLabel: string;
  submitCta: string;
  submittingCta: string;
  successTitle: string;
  successTemplate: string;
  successRouteTemplate: string;
  afterHoursNote: string;
  validation: {
    required: string;
    email: string;
    consent: string;
    messageLength: string;
    fileType: string;
    fileSize: string;
  };
  routingLabel: string;
  routingNotePrefix: string;
  languageOptions: Array<{ value: LanguageChoice; label: string }>;
  topicOptions: Array<{ value: Topic; label: string }>;
};

type RoutingInfo = {
  [key in Topic]: {
    destination: string;
    note: string;
  };
};

type SmartContactFormProps = {
  lang: Lang;
  copy: FormCopy;
  routingInfo: RoutingInfo;
};

interface FormValues {
  name: string;
  email: string;
  phone: string;
  company: string;
  topic: Topic | "";
  message: string;
  consent: boolean;
  language: LanguageChoice;
}

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

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

export default function SmartContactForm({
  lang,
  copy,
  routingInfo,
}: SmartContactFormProps) {
  const { executeRecaptcha } = useGoogleReCaptcha();

  const [formState, setFormState] = useState<FormState>("idle");
  const [formData, setFormData] = useState<FormValues>({
    name: "",
    email: "",
    phone: "",
    company: "",
    topic: "",
    message: "",
    consent: false,
    language: lang,
  });
  const [files, setFiles] = useState<FileWithPreview[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [errorMessage, setErrorMessage] = useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [isDragging, setIsDragging] = useState(false);
  const [routeNote, setRouteNote] = useState<string | null>(null);

  // Cleanup blob URLs on unmount to prevent memory leaks
  useEffect(() => {
    return () => {
      files.forEach((fileObj) => {
        if (fileObj.preview) {
          URL.revokeObjectURL(fileObj.preview);
        }
      });
    };
  }, [files]);

  // Update routing note when topic 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,
    }));

    // Update routing note for topic changes
    if (name === "topic" && value && routingInfo[value as Topic]) {
      setRouteNote(
        `${copy.routingNotePrefix} ${routingInfo[value as Topic].destination}`,
      );
    } else if (name === "topic") {
      setRouteNote(null);
    }

    // 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("Too many files. Maximum is 3 files");
          return;
        }

        // Check file size
        if (file.size > FILE_UPLOAD_CONFIG.maxSizeBytes) {
          validationErrors.push(copy.validation.fileSize);
          return;
        }

        // Check file extension
        const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0] || "";
        if (!FILE_UPLOAD_CONFIG.allowedExtensions.includes(extension as any)) {
          validationErrors.push(
            "Invalid file extension. Allowed: JPEG, PNG, GIF, WebP, PDF",
          );
          return;
        }

        // Check MIME type
        if (!FILE_UPLOAD_CONFIG.allowedMimeTypes.includes(file.type as any)) {
          validationErrors.push(copy.validation.fileType);
          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, copy.validation],
  );

  // 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];
      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 = copy.validation.required;
    }
    if (!formData.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = copy.validation.email;
    }
    if (!formData.topic) {
      newErrors.topic = copy.validation.required;
    }
    if (!formData.message || formData.message.trim().length < 10) {
      newErrors.message = copy.validation.messageLength;
    } else if (formData.message.trim().length > 10000) {
      newErrors.message = "Message must be less than 10,000 characters";
    }
    if (!formData.consent) {
      newErrors.consent = copy.validation.consent;
    }

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

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

    if (!validateForm()) {
      return;
    }

    try {
      setFormState("submitting");

      let recaptchaToken = "";
      if (executeRecaptcha) {
        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.language);
      submitData.append("consentGiven", formData.consent.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(
            "Too many submissions. Please wait 5 minutes and try again.",
          );
        } else if (result.errors) {
          const fieldErrors: Record<string, string> = {};
          result.errors.forEach((err: any) => {
            fieldErrors[err.field] = err.message;
          });
          setErrors(fieldErrors);
          setErrorMessage("Please correct the errors above and try again.");
        } else {
          setErrorMessage(
            result.error || "Something went wrong. Please try again.",
          );
        }
        setFormState("error");
        return;
      }

      // Success!
      const ticketId = `#${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, "0")}${String(new Date().getDate()).padStart(2, "0")}-${result.submissionId.slice(0, 4)}`;
      let message = copy.successTemplate.replace("%ticket%", ticketId);

      if (formData.topic && routingInfo[formData.topic]) {
        const route = routingInfo[formData.topic];
        const routeText = `${route.destination} — ${route.note}`;
        message += copy.successRouteTemplate.replace("%route%", routeText);
      }

      setSuccessMessage(message);
      setFormState("success");

      // Reset form and cleanup blob URLs
      files.forEach((fileObj) => {
        if (fileObj.preview) {
          URL.revokeObjectURL(fileObj.preview);
        }
      });

      setFormData({
        name: "",
        email: "",
        phone: "",
        company: "",
        topic: "",
        message: "",
        consent: false,
        language: lang,
      });
      setFiles([]);
      setErrors({});
    } catch (error) {
      console.error("Form submission error:", error);
      setErrorMessage(
        "Network error. Please check your connection and try again.",
      );
      setFormState("error");
    }
  };

  // Success state
  if (formState === "success" && successMessage) {
    return (
      <div className="text-center py-8">
        <div className="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <Check className="w-8 h-8 text-emerald-600" />
        </div>
        <h3 className="text-2xl font-bold text-neutral-900 mb-4">
          {copy.successTitle}
        </h3>
        <p className="text-neutral-600 whitespace-pre-line">{successMessage}</p>
        <button
          onClick={() => {
            setFormState("idle");
            setSuccessMessage("");
          }}
          className="mt-6 inline-flex items-center px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-green-600 transition-colors"
        >
          Send Another Message
        </button>
      </div>
    );
  }

  return (
    <form className="space-y-6" onSubmit={handleSubmit} noValidate>
      {/* Error banner */}
      {errorMessage && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
          <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-red-700">{errorMessage}</p>
        </div>
      )}

      {/* Name and Email */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label
            htmlFor="contact-name"
            className="block text-sm font-medium text-neutral-700"
          >
            {copy.nameLabel} <span className="text-red-500">*</span>
          </label>
          <input
            id="contact-name"
            name="name"
            type="text"
            value={formData.name}
            onChange={handleChange}
            className={`mt-2 w-full rounded-lg border ${errors.name ? "border-red-500" : "border-neutral-300"} bg-white px-4 py-3 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
            autoComplete="name"
            disabled={formState === "submitting"}
            required
          />
          {errors.name && (
            <p className="mt-2 text-sm text-red-600">{errors.name}</p>
          )}
        </div>

        <div>
          <label
            htmlFor="contact-email"
            className="block text-sm font-medium text-neutral-700"
          >
            {copy.emailLabel} <span className="text-red-500">*</span>
          </label>
          <input
            id="contact-email"
            name="email"
            type="email"
            value={formData.email}
            onChange={handleChange}
            className={`mt-2 w-full rounded-lg border ${errors.email ? "border-red-500" : "border-neutral-300"} bg-white px-4 py-3 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
            autoComplete="email"
            disabled={formState === "submitting"}
            required
          />
          {errors.email && (
            <p className="mt-2 text-sm text-red-600">{errors.email}</p>
          )}
        </div>
      </div>

      {/* Phone and Company */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label
            htmlFor="contact-phone"
            className="block text-sm font-medium text-neutral-700"
          >
            {copy.phoneLabel}
          </label>
          <input
            id="contact-phone"
            name="phone"
            type="tel"
            value={formData.phone}
            onChange={handleChange}
            className="mt-2 w-full rounded-lg border border-neutral-300 bg-white px-4 py-3 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
            autoComplete="tel"
            placeholder={copy.phoneHint}
            disabled={formState === "submitting"}
          />
          <p className="mt-2 text-sm text-neutral-500">{copy.phoneHint}</p>
        </div>

        <div>
          <label
            htmlFor="contact-company"
            className="block text-sm font-medium text-neutral-700"
          >
            {copy.companyLabel}
          </label>
          <input
            id="contact-company"
            name="company"
            type="text"
            value={formData.company}
            onChange={handleChange}
            className="mt-2 w-full rounded-lg border border-neutral-300 bg-white px-4 py-3 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
            autoComplete="organization"
            disabled={formState === "submitting"}
          />
        </div>
      </div>

      {/* Topic dropdown */}
      <div>
        <label
          htmlFor="contact-topic"
          className="block text-sm font-medium text-neutral-700"
        >
          {copy.topicLabel} <span className="text-red-500">*</span>
        </label>
        <select
          id="contact-topic"
          name="topic"
          value={formData.topic}
          onChange={handleChange}
          className={`mt-2 w-full rounded-lg border ${errors.topic ? "border-red-500" : "border-neutral-300"} bg-white px-4 py-3 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20`}
          disabled={formState === "submitting"}
          required
        >
          <option value="">{copy.topicPlaceholder}</option>
          {copy.topicOptions.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        {routeNote && (
          <p className="mt-2 text-sm text-brand-green">
            {copy.routingLabel} {routeNote}
          </p>
        )}
        {errors.topic && (
          <p className="mt-2 text-sm text-red-600">{errors.topic}</p>
        )}
      </div>

      {/* Message textarea */}
      <div>
        <label
          htmlFor="contact-message"
          className="block text-sm font-medium text-neutral-700"
        >
          {copy.messageLabel} <span className="text-red-500">*</span>
        </label>
        <textarea
          id="contact-message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          className={`mt-2 w-full rounded-lg border ${errors.message ? "border-red-500" : "border-neutral-300"} bg-white px-4 py-3 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20 resize-none`}
          rows={6}
          placeholder={copy.messagePlaceholder}
          disabled={formState === "submitting"}
          required
        />
        <div className="mt-2 flex items-center justify-between text-sm text-neutral-500">
          <span>{formData.message.length}/10000</span>
          {copy.afterHoursNote && (
            <span className="text-xs">{copy.afterHoursNote}</span>
          )}
        </div>
        {errors.message && (
          <p className="mt-2 text-sm text-red-600">{errors.message}</p>
        )}
      </div>

      {/* File upload */}
      <div>
        <label className="block text-sm font-medium text-neutral-700 mb-2">
          {copy.attachmentsLabel}
        </label>
        <div
          className={`border-2 border-dashed ${isDragging ? "border-brand-green bg-green-50" : "border-neutral-300"} 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 mb-2">
            Drag and drop files here, or click to browse
          </p>
          <p className="text-xs text-gray-500">{copy.attachmentsHint}</p>
          <input
            type="file"
            id="file-upload"
            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 text-sm"
          >
            {copy.attachmentsLabel}
          </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 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 truncate">
                    {fileObj.file.name}
                  </p>
                  <p className="text-xs text-gray-500">
                    {(fileObj.file.size / 1024 / 1024).toFixed(2)} MB
                  </p>
                </div>
                <button
                  type="button"
                  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>

      {/* Preferred language */}
      <div>
        <fieldset className="space-y-3">
          <legend className="text-sm font-medium text-neutral-700">
            {copy.languageLabel}
          </legend>
          <div className="flex flex-wrap gap-3">
            {copy.languageOptions.map((option) => (
              <label
                key={option.value}
                className="flex items-center gap-2 rounded-full border border-neutral-300 px-4 py-2 text-sm cursor-pointer hover:border-brand-green transition-colors"
              >
                <input
                  type="radio"
                  name="language"
                  value={option.value}
                  checked={formData.language === option.value}
                  onChange={handleChange}
                  disabled={formState === "submitting"}
                />
                <span>{option.label}</span>
              </label>
            ))}
          </div>
        </fieldset>
      </div>

      {/* Consent checkbox */}
      <div className="flex items-start gap-3">
        <input
          id="contact-consent"
          name="consent"
          type="checkbox"
          checked={formData.consent}
          onChange={handleChange}
          className="mt-1 h-5 w-5 rounded border-neutral-300 text-brand-green focus:ring-brand-green"
          disabled={formState === "submitting"}
          required
        />
        <label
          htmlFor="contact-consent"
          className={`text-sm ${errors.consent ? "text-red-600" : "text-neutral-700"}`}
        >
          {copy.consentLabel}
        </label>
      </div>
      {errors.consent && (
        <p className="text-sm text-red-600">{errors.consent}</p>
      )}

      {/* Submit button */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <button
          type="submit"
          className="inline-flex items-center justify-center rounded-lg bg-brand-green px-6 py-3 font-semibold text-white shadow-sm transition hover:bg-green-600 disabled:cursor-not-allowed disabled:opacity-70 gap-2"
          disabled={formState === "submitting"}
        >
          {formState === "submitting" && (
            <Loader2 className="w-5 h-5 animate-spin" />
          )}
          {formState === "submitting" ? copy.submittingCta : copy.submitCta}
        </button>
      </div>

      {/* reCAPTCHA disclaimer - TEMPORARILY DISABLED */}
      {/* <p className="text-xs text-center text-gray-500">
        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>
  );
}
