"use client";

import { useQuoteStore } from "@/lib/quote-store";
import { type FormEvent, useState } from "react";
import { z } from "zod";
import axios from "axios";
import { User, Mail, Phone, MessageSquare } from "lucide-react";

import { useToast } from "@/hooks/use-toast";

// Define the schema for the quote form
const quoteFormSchema = 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(),
});

interface QuoteFormProps {
  items: ReturnType<typeof useQuoteStore.getState>["items"];
}

export default function QuoteForm({ items }: QuoteFormProps) {
  const { toast } = useToast();
  const { clearItems } = useQuoteStore();
  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 handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setFile(e.target.files[0]);
    }
  };

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

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

    // Parse products as array for validation
    let products: { id: number; quantity: number }[] = items.map((item) => ({
      id: item.id,
      quantity: item.quantity,
    }));

    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() || "",
      products,
    };

    // Validate the form data (including products)
    const schema = quoteFormSchema.extend({
      products: z.array(
        z.object({
          id: z.number(),
          quantity: z.number().min(1),
        })
      ),
      // file is optional
      file: z.any().optional(),
    });
    const result = schema.safeParse({ ...formValues, file });
    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 {
      // Prepare FormData for Laravel controller
      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);
      formValues.products.forEach((prod, idx) => {
        sendData.append(`products[${idx}][id]`, prod.id.toString());
        sendData.append(`products[${idx}][quantity]`, prod.quantity.toString());
      });
      if (file) {
        sendData.append("file", file);
      }

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

      if (!response.ok) {
        throw new Error("Failed to submit quote request. Please try again.");
      }

      toast({
        title: "Quote request submitted successfully!",
        description: "Your have submited your quote.",
      });

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

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

      <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 border ${
            errors.full_name ? "border-red-300" : "border-gray-300"
          } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent`}
        />
        {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 border ${
            errors.email ? "border-red-300" : "border-gray-300"
          } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent`}
        />
        {errors.email && (
          <p className="mt-1 text-sm text-red-600">{errors.email}</p>
        )}
      </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 border ${
            errors.phone ? "border-red-300" : "border-gray-300"
          } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent`}
        />
        {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 border ${
            errors.message ? "border-red-300" : "border-gray-300"
          } rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent`}
        ></textarea>
        {errors.message && (
          <p className="mt-1 text-sm text-red-600">{errors.message}</p>
        )}
      </div>

      <div className="relative">
        <label className="block text-gray-700 mb-2">
          Attach a file (optional):
        </label>
        <input
          type="file"
          name="file"
          onChange={handleFileChange}
          className="w-full px-4 py-2 rounded-lg bg-white border border-gray-300 file:bg-red-600 file:text-white file:rounded file:px-4 file:py-2 file:border-none focus:outline-none focus:border-red-600 transition-colors"
        />
        {file && (
          <span className="text-xs mt-1 block text-gray-600">
            Selected: {file.name}
          </span>
        )}
      </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`}
      >
        {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...
          </>
        ) : (
          "Request a Quote"
        )}
      </button>
    </form>
  );
}
