"use client";

import { useState } from "react";
import { ChevronDown } from "lucide-react";
import React from "react";
import { useLocale, useTranslations } from "next-intl";

/** Data shape matching what Markatty's saveaddress expects */
export interface ShippingFormData {
    first_name: string;
    last_name: string;
    email: string;
    address1: string;
    city: string;
    state: string;
    country: string;
    postcode: string;
    phone: string;
}

export interface ShippingFormProps {
    onSubmit: (data: ShippingFormData) => void;
    isLoading?: boolean;
}

const egyptianCities = [
    "القاهرة",
    "الإسكندرية",
    "الجيزة",
    "شبرا الخيمة",
    "بورسعيد",
    "السويس",
    "الأقصر",
    "أسوان",
    "المنصورة",
    "طنطا",
    "الزقازيق",
    "دمياط",
];

/**
 * Shipping address form — fields match Markatty's saveaddress API.
 * Sends: first_name, last_name, email, address1, city, state, country, postcode, phone.
 */
export default function ShippingForm({ onSubmit, isLoading = false }: ShippingFormProps) {
    const t = useTranslations("cart");
    const tValidation = useTranslations("validation");
    const locale = useLocale();
    const isRtl = locale === "ar";
    const [formData, setFormData] = useState<ShippingFormData>({
        first_name: "",
        last_name: "",
        email: "",
        address1: "",
        city: "",
        state: "",
        country: "EG",
        postcode: "",
        phone: "",
    });

    const [errors, setErrors] = useState<Partial<Record<keyof ShippingFormData, string>>>({});

    const validate = (): boolean => {
        const newErrors: Partial<Record<keyof ShippingFormData, string>> = {};

        if (!formData.first_name.trim()) {
            newErrors.first_name = tValidation("first-name-required");
        } else if (formData.first_name.trim().length < 2) {
            newErrors.first_name = tValidation("first-name-required");
        }

        if (!formData.last_name.trim()) {
            newErrors.last_name = tValidation("last-name-required");
        } else if (formData.last_name.trim().length < 2) {
            newErrors.last_name = tValidation("last-name-required");
        }

        if (!formData.phone.trim()) {
            newErrors.phone = tValidation("phone-required");
        } else if (formData.phone.replace(/\D/g, "").length < 9) {
            newErrors.phone = tValidation("phone-invalid");
        }

        if (!formData.city.trim()) newErrors.city = tValidation("city-required");
        if (!formData.address1.trim()) newErrors.address1 = tValidation("address-required");

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

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (!validate()) return;

        onSubmit({
            ...formData,
            state: formData.state || formData.city,
            postcode: formData.postcode || "00000",
        });
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
        if (errors[name as keyof ShippingFormData]) {
            setErrors((prev) => ({ ...prev, [name]: "" }));
        }
    };

    const inputClass = (field: keyof ShippingFormData) =>
        `w-full border rounded-lg py-3 px-4 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 focus:ring-black focus:border-black text-start transition ${errors[field]
            ? "border-red-400 dark:border-red-500"
            : "border-gray-300 dark:border-gray-600"
        }`;

    return (
        <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-3 gap-5" dir={isRtl ? "rtl" : "ltr"}>
            {/* First Name */}
            <div className="md:col-span-1">
                <label className="block text-xs text-gray-400 mb-1 text-start">{t("first-name")} *</label>
                <input
                    type="text"
                    name="first_name"
                    value={formData.first_name}
                    onChange={handleChange}
                    className={inputClass("first_name")}
                    disabled={isLoading}
                />
                {errors.first_name && <p className="text-red-500 text-xs mt-1">{errors.first_name}</p>}
            </div>

            {/* Last Name */}
            <div className="md:col-span-1">
                <label className="block text-xs text-gray-400 mb-1 text-start">{t("last-name")} *</label>
                <input
                    type="text"
                    name="last_name"
                    value={formData.last_name}
                    onChange={handleChange}
                    className={inputClass("last_name")}
                    disabled={isLoading}
                />
                {errors.last_name && <p className="text-red-500 text-xs mt-1">{errors.last_name}</p>}
            </div>

            {/* Phone */}
            <div className="md:col-span-1">
                <label className="block text-xs text-gray-400 mb-1 text-start">{t("phone")} *</label>
                <div className="flex items-center border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-800">
                    <div className="px-3 flex items-center border-l border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700/50 h-[46px]">
                        <img
                            alt="EG Flag"
                            className="w-6 h-auto ml-1"
                            src="https://flagcdn.com/w40/eg.png"
                        />
                    </div>
                    <input
                        type="tel"
                        name="phone"
                        value={formData.phone}
                        onChange={handleChange}
                        className="w-full border-0 py-3 px-4 text-left text-gray-700 dark:text-gray-300 bg-transparent focus:ring-0 h-[46px]"
                        dir="ltr"
                        placeholder="+20 1xxxxxxxxx"
                        disabled={isLoading}
                    />
                </div>
                {errors.phone && <p className="text-red-500 text-xs mt-1">{errors.phone}</p>}
            </div>

            {/* Email */}
            <div className="md:col-span-1">
                <label className="block text-xs text-gray-400 mb-1 text-start">{t("email")}</label>
                <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    className={inputClass("email")}
                    dir="ltr"
                    disabled={isLoading}
                />
            </div>

            {/* City */}
            <div className="md:col-span-1">
                <label className="block text-xs text-gray-400 mb-1 text-start">{t("city")} *</label>
                <div className="relative">
                    <select
                        name="city"
                        value={formData.city}
                        onChange={handleChange}
                        className={`${inputClass("city")} appearance-none`}
                        disabled={isLoading}
                    >
                        <option value="">{t("select-city")}</option>
                        {egyptianCities.map((city) => (
                            <option key={city} value={city}>{city}</option>
                        ))}
                    </select>
                    <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center px-4 text-gray-500">
                        <ChevronDown className="w-5 h-5" />
                    </div>
                </div>
                {errors.city && <p className="text-red-500 text-xs mt-1">{errors.city}</p>}
            </div>

            {/* Postcode */}
            <div className="md:col-span-1">
                <label className="block text-xs text-gray-400 mb-1 text-start">Postcode</label>
                <input
                    type="text"
                    name="postcode"
                    value={formData.postcode}
                    onChange={handleChange}
                    className={inputClass("postcode")}
                    disabled={isLoading}
                />
            </div>

            {/* Address (full row) */}
            <div className="md:col-span-3">
                <label className="block text-xs text-gray-400 mb-1 text-start">{t("address")} *</label>
                <input
                    type="text"
                    name="address1"
                    value={formData.address1}
                    onChange={handleChange}
                    className={inputClass("address1")}
                    disabled={isLoading}
                />
                {errors.address1 && <p className="text-red-500 text-xs mt-1">{errors.address1}</p>}
            </div>

            {/* Submit Button */}
            <div className="md:col-span-3 flex justify-start mt-2">
                <button
                    type="submit"
                    disabled={isLoading}
                    className="px-8 bg-black text-white py-3.5 rounded-lg font-bold text-base hover:opacity-90 transition shadow-lg whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {isLoading ? t("saving") : t("send-to-this-address")}
                </button>
            </div>
        </form>
    );
}
