"use client";

import { useState } from "react";
import classNames from "classnames";
import type { Lang } from "@/lib/config";

interface CompanyFormProps {
  lang: Lang;
  isAr: boolean;
  dict: any;
  industries: Array<{ value: string; labelEn: string; labelAr: string }>;
  companySizes: Array<{ value: string; labelEn: string; labelAr: string }>;
  locations: any;
  onSubmit: (data: any) => Promise<void>;
  loading: boolean;
}

export default function CompanyForm({
  lang,
  isAr,
  dict,
  industries,
  companySizes,
  locations,
  onSubmit,
  loading,
}: CompanyFormProps) {
  const [formData, setFormData] = useState({
    companyName: "",
    industry: "",
    companySize: "",
    country: "",
    city: "",
    phoneNumber: "",
    website: "",
  });

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

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

    if (!formData.companyName.trim()) {
      newErrors.companyName = isAr
        ? "اسم الشركة مطلوب"
        : "Company name is required";
    } else if (formData.companyName.length < 2) {
      newErrors.companyName = isAr
        ? "اسم الشركة قصير جداً"
        : "Company name is too short";
    }

    if (!formData.industry) {
      newErrors.industry = isAr
        ? "يرجى اختيار الصناعة"
        : "Please select an industry";
    }

    if (!formData.companySize) {
      newErrors.companySize = isAr
        ? "يرجى اختيار حجم الشركة"
        : "Please select company size";
    }

    if (!formData.country) {
      newErrors.country = isAr ? "يرجى اختيار البلد" : "Please select country";
    }

    // Phone validation (optional)
    if (formData.phoneNumber && !/^\+?[\d\s-()]+$/.test(formData.phoneNumber)) {
      newErrors.phoneNumber = isAr
        ? "رقم الهاتف غير صالح"
        : "Invalid phone number";
    }

    // Website validation (optional)
    if (formData.website) {
      try {
        const url = new URL(
          formData.website.startsWith("http")
            ? formData.website
            : `https://${formData.website}`,
        );
        if (!url.hostname.includes(".")) {
          newErrors.website = isAr
            ? "رابط الموقع غير صالح"
            : "Invalid website URL";
        }
      } catch {
        newErrors.website = isAr
          ? "رابط الموقع غير صالح"
          : "Invalid website URL";
      }
    }

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    await onSubmit(formData);
  };

  // Get cities based on selected country
  const getCities = () => {
    if (!formData.country) return [];
    return locations[formData.country] || [];
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6" dir={dict.dir}>
      {/* Company Name */}
      <div>
        <label
          htmlFor="companyName"
          className="block text-sm font-medium text-neutral-700 mb-1"
        >
          {isAr ? "اسم الشركة" : "Company Name"} *
        </label>
        <input
          id="companyName"
          type="text"
          value={formData.companyName}
          onChange={(e) =>
            setFormData({ ...formData, companyName: e.target.value })
          }
          className={classNames(
            "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
            errors.companyName
              ? "border-red-300 focus:border-red-500 focus:ring-red-200"
              : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
          )}
          placeholder={
            isAr
              ? "مثال: عيادة النور الطبية"
              : "Example: Sunshine Medical Clinic"
          }
        />
        {errors.companyName && (
          <p className="mt-1 text-xs text-red-600">{errors.companyName}</p>
        )}
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {/* Industry */}
        <div>
          <label
            htmlFor="industry"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr ? "الصناعة" : "Industry"} *
          </label>
          <select
            id="industry"
            value={formData.industry}
            onChange={(e) =>
              setFormData({ ...formData, industry: e.target.value })
            }
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              errors.industry
                ? "border-red-300 focus:border-red-500 focus:ring-red-200"
                : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
            )}
          >
            <option value="">
              {isAr ? "اختر الصناعة" : "Select Industry"}
            </option>
            {industries.map((industry) => (
              <option key={industry.value} value={industry.value}>
                {isAr ? industry.labelAr : industry.labelEn}
              </option>
            ))}
          </select>
          {errors.industry && (
            <p className="mt-1 text-xs text-red-600">{errors.industry}</p>
          )}
        </div>

        {/* Company Size */}
        <div>
          <label
            htmlFor="companySize"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr ? "حجم الشركة" : "Company Size"} *
          </label>
          <select
            id="companySize"
            value={formData.companySize}
            onChange={(e) =>
              setFormData({ ...formData, companySize: e.target.value })
            }
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              errors.companySize
                ? "border-red-300 focus:border-red-500 focus:ring-red-200"
                : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
            )}
          >
            <option value="">{isAr ? "اختر حجم الشركة" : "Select Size"}</option>
            {companySizes.map((size) => (
              <option key={size.value} value={size.value}>
                {isAr ? size.labelAr : size.labelEn}
              </option>
            ))}
          </select>
          {errors.companySize && (
            <p className="mt-1 text-xs text-red-600">{errors.companySize}</p>
          )}
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {/* Country */}
        <div>
          <label
            htmlFor="country"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr ? "البلد" : "Country"} *
          </label>
          <select
            id="country"
            value={formData.country}
            onChange={(e) =>
              setFormData({ ...formData, country: e.target.value, city: "" })
            }
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              errors.country
                ? "border-red-300 focus:border-red-500 focus:ring-red-200"
                : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
            )}
          >
            <option value="">{isAr ? "اختر البلد" : "Select Country"}</option>
            {Object.keys(locations).map((country) => (
              <option key={country} value={country}>
                {country}
              </option>
            ))}
          </select>
          {errors.country && (
            <p className="mt-1 text-xs text-red-600">{errors.country}</p>
          )}
        </div>

        {/* City */}
        <div>
          <label
            htmlFor="city"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr ? "المدينة" : "City"}
          </label>
          <select
            id="city"
            value={formData.city}
            onChange={(e) => setFormData({ ...formData, city: e.target.value })}
            disabled={!formData.country}
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
              !formData.country && "bg-neutral-50 cursor-not-allowed",
            )}
          >
            <option value="">{isAr ? "اختر المدينة" : "Select City"}</option>
            {getCities().map((city: any) => (
              <option key={city.value} value={city.value}>
                {isAr ? city.labelAr : city.labelEn}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {/* Phone Number */}
        <div>
          <label
            htmlFor="phoneNumber"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr ? "رقم الهاتف" : "Phone Number"}
            <span className="text-neutral-400 text-xs ml-2">
              ({isAr ? "اختياري" : "Optional"})
            </span>
          </label>
          <input
            id="phoneNumber"
            type="tel"
            value={formData.phoneNumber}
            onChange={(e) =>
              setFormData({ ...formData, phoneNumber: e.target.value })
            }
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              errors.phoneNumber
                ? "border-red-300 focus:border-red-500 focus:ring-red-200"
                : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
            )}
            placeholder="+971 50 123 4567"
            dir="ltr"
          />
          {errors.phoneNumber && (
            <p className="mt-1 text-xs text-red-600">{errors.phoneNumber}</p>
          )}
        </div>

        {/* Website */}
        <div>
          <label
            htmlFor="website"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr ? "الموقع الإلكتروني" : "Website"}
            <span className="text-neutral-400 text-xs ml-2">
              ({isAr ? "اختياري" : "Optional"})
            </span>
          </label>
          <input
            id="website"
            type="text"
            value={formData.website}
            onChange={(e) =>
              setFormData({ ...formData, website: e.target.value })
            }
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              errors.website
                ? "border-red-300 focus:border-red-500 focus:ring-red-200"
                : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
            )}
            placeholder="www.example.com"
            dir="ltr"
          />
          {errors.website && (
            <p className="mt-1 text-xs text-red-600">{errors.website}</p>
          )}
        </div>
      </div>

      {/* Submit Button */}
      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-lg bg-brand-green px-4 py-3 text-sm font-semibold text-white transition-all hover:bg-brand-green/90 focus:outline-none focus:ring-2 focus:ring-brand-green/20 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {loading
          ? isAr
            ? "جاري الحفظ..."
            : "Saving..."
          : isAr
            ? "التالي"
            : "Next"}
      </button>
    </form>
  );
}
