"use client";

import { useToast } from "@/hooks/use-toast";
import { getContacts } from "@/lib/api";
import { z } from "zod";
import { type FormEvent, useEffect, useState } from "react";
import axios from "axios";
import { Mail, MessageSquare, Phone, User } from "lucide-react";
import Image from "next/image";

// Define the schema for the contact form
const contactFormSchema = z.object({
  full_name: z.string().min(1, { message: "Full name is required." }).trim(),
  email: z.string().email("Invalid email address.").trim(),
  phone: z.string().min(1, { message: "Phone number is required." }).trim(),
  message: z.string().min(1, { message: "Message is required." }).trim(),
  file: z.any().optional(),
});

const MAX_FILE_SIZE = 300 * 1024 * 1024; // 300MB in bytes

interface Contacts {
  phone1: string | null;
  phone2: string | null;
  phone3: string | null;
  phone4: string | null;
  email: string | null;
  email2: string | null;
  address: string | null;
  gmapUrl: string | null;
  business_hours: string | null;
  qr: string | null;
}
export default function ContactForm() {
  const { toast } = useToast();
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [file, setFile] = useState<File | null>(null);

  const [contacts, setContacts] = useState<Contacts>();
  useEffect(() => {
    const fetchContacts = async () => {
      const resp = await getContacts();
      setContacts(resp);
    };
    fetchContacts();
  }, []);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const selectedFile = e.target.files[0];

      if (selectedFile.size > MAX_FILE_SIZE) {
        toast({
          title: "File too large",
          description: "Please select a file smaller than 300MB",
          variant: "destructive",
        });
        e.target.value = ''; // Clear the file input
        setFile(null);
        return;
      }

      setFile(selectedFile);
    }
  };

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrors({});
    setErrorMessage(null);

    const form = e.currentTarget;
    const formData = new FormData(form);

    const formValues = {
      full_name: formData.get("full_name")?.toString().trim() || "",
      email: formData.get("email")?.toString().trim() || "",
      phone: formData.get("phone")?.toString().trim() || "",
      message: formData.get("message")?.toString().trim() || "",
      file,
    };

    // Validate the form data
    const result = contactFormSchema.safeParse(formValues);
    if (!result.success) {
      const fieldErrors: Record<string, string> = {};
      result.error.errors.forEach((err) => {
        fieldErrors[err.path[0]] = err.message;
      });
      setErrors(fieldErrors);
      return;
    }

    setLoading(true);

    try {
      const sendData = new FormData();
      sendData.append("full_name", formValues.full_name);
      sendData.append("email", formValues.email);
      sendData.append("phone", formValues.phone);
      sendData.append("message", formValues.message);
      if (file) {
        sendData.append("file", file);
      }

      const res = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/api/contacts`,
        {
          method: "POST",
          body: sendData,
        }
      );

      if (!res.ok) {
        throw new Error("Failed to submit contact form. Please try again.");
      }

      toast({
        title: "Message sent successfully!",
        description: "Your message has been sent.",
      });

      form.reset();
      setFile(null);
    } catch (err) {
      const message =
        err instanceof Error ? err.message : "Failed to submit contact form";
      setErrorMessage(message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-6 bg-white/10 rounded-xl shadow-lg">
      {/* QR Code Section */}
      {contacts?.qr && (
      <div className="mb-8 text-center">
        <h3 className="text-xl font-semibold text-gray-100 mb-4">Scan QR Code to Contact Us</h3>
        <div className="inline-block p-4 bg-gray-50 rounded-lg border border-gray-200">
          <Image
            src={`${process.env.NEXT_PUBLIC_API_URL}/storage/${contacts?.qr}` || ""}
            alt="QR Code"
            width={200}
            height={200}
            className="rounded-lg"
          />
        </div>
      </div>
      )}
      {/* Contact Form Section */}
      <div className="space-y-6">
        <div className="text-center mb-6">
          <h2 className="text-2xl font-bold text-gray-100">Get in Touch</h2>
          <p className="mt-2 text-gray-400">Fill out the form below and we'll get back to you shortly</p>
        </div>

        <form
          onSubmit={handleSubmit}
          className="space-y-5"
          encType="multipart/form-data"
        >
          {errorMessage && (
            <div className="bg-white/10 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-4">
              {errorMessage}
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            <div className="relative">
              <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-400">
                <User className="w-5 h-5" />
              </div>
              <input
                type="text"
                name="full_name"
                id="full_name"
                placeholder="Your Full Name"
                className={`w-full pl-10 pr-4 py-3 bg-white/10 border ${errors.full_name ? "border-red-300" : "border-white/20"
                  } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-colors`}
              />
              {errors.full_name && (
                <p className="mt-1 text-sm text-red-600">{errors.full_name}</p>
              )}
            </div>

            <div className="relative">
              <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-400">
                <Mail className="w-5 h-5" />
              </div>
              <input
                type="email"
                name="email"
                id="email"
                placeholder="Email Address"
                className={`w-full pl-10 pr-4 py-3 bg-white/10 border ${errors.email ? "border-red-300" : "border-white/20"
                  } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-colors`}
              />
              {errors.email && (
                <p className="mt-1 text-sm text-red-600">{errors.email}</p>
              )}
            </div>
          </div>

          <div className="relative">
            <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-400">
              <Phone className="w-5 h-5" />
            </div>
            <input
              type="tel"
              name="phone"
              id="phone"
              placeholder="Phone Number"
              className={`w-full pl-10 pr-4 py-3 bg-white/10 border ${errors.phone ? "border-red-300" : "border-white/20"
                } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-colors`}
            />
            {errors.phone && (
              <p className="mt-1 text-sm text-red-600">{errors.phone}</p>
            )}
          </div>

          <div className="relative">
            <div className="absolute top-3 left-0 flex items-start pl-3 pointer-events-none text-gray-400">
              <MessageSquare className="w-5 h-5" />
            </div>
            <textarea
              name="message"
              id="message"
              rows={4}
              placeholder="Your Message"
              className={`w-full pl-10 pr-4 py-3 bg-white/10 border ${errors.message ? "border-red-300" : "border-white/20"
                } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-colors`}
            ></textarea>
            {errors.message && (
              <p className="mt-1 text-sm text-red-600">{errors.message}</p>
            )}
          </div>

          <div className="relative">
            <label className="block text-gray-400 font-medium mb-2">
              Attach a file (optional, max 300MB)
            </label>
            <input
              type="file"
              name="file"
              onChange={handleFileChange}
              className="w-full px-4 py-2 rounded-lg bg-white/10 border border-white/20 file:bg-red-600 file:text-white file:rounded file:px-4 file:py-2 file:border-none hover:file:bg-red-700 focus:outline-none focus:border-red-600 transition-colors"
            />
            {file && (
              <div className="mt-2 space-y-1">
                <span className="text-sm block text-gray-400">
                  Selected: {file.name}
                </span>
                <span className="text-xs block text-gray-500">
                  Size: {(file.size / (1024 * 1024)).toFixed(2)}MB
                </span>
              </div>
            )}
          </div>

          <button
            type="submit"
            disabled={loading}
            className={`w-full py-3 px-4 ${loading ? "bg-gray-400" : "bg-red-600 hover:bg-red-700"
              } text-white rounded-lg transition-colors flex items-center justify-center font-medium text-lg shadow-sm hover:shadow-md`}
          >
            {loading ? (
              <>
                <svg
                  className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  ></path>
                </svg>
                Submitting...
              </>
            ) : (
              "Send Message"
            )}
          </button>
        </form>
      </div>
    </div>
  );
}
