"use client";

import React, { useEffect, useState, ChangeEvent } from "react";
import { FaFlag } from "react-icons/fa";
import toast from "react-hot-toast";
import styles from "./../../companies/Form/FormStyles.module.css";   // ✅ shared generic CSS
import { createCountry, updateCountry, getCountry } from "@/lib/api/country.api";
import type { CreateCountryDto } from "@/lib/api/types/country.types";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  refreshData?: () => void;
  editId?: number | null;
}

const DEFAULT: CreateCountryDto = { name: "", code: "", flag_url: "" };

export default function CountryForm({ isOpen, onClose, refreshData, editId }: Props) {
  const isEdit = Boolean(editId);
  const [form, setForm]         = useState<CreateCountryDto>({ ...DEFAULT });
  const [errors, setErrors]     = useState<Record<string, string>>({});
  const [touched, setTouched]   = useState<Record<string, boolean>>({});
  const [saving, setSaving]     = useState(false);
  const [loadingEdit, setLoadingEdit] = useState(false);

  // Hydrate on edit
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getCountry(editId)
        .then((c) => setForm({ name: c.name || "", code: c.code || "", flag_url: c.flag_url || "" }))
        .catch(() => toast.error("Failed to load country"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT }); setErrors({}); setTouched({});
    }
  }, [isOpen, editId]);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm((p) => ({ ...p, [name]: value }));
    setTouched((p) => ({ ...p, [name]: true }));
    setErrors((p) => ({ ...p, [name]: "" }));
  };

  const showErr = (key: string) => !!(errors[key] && touched[key]);

  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.name.trim()) e.name = "Country name is required";
    if (!form.code.trim()) e.code = "Country code is required";
    setErrors(e);
    setTouched((p) => ({ ...p, ...Object.fromEntries(Object.keys(e).map((k) => [k, true])) }));
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setSaving(true);
    try {
      if (isEdit && editId) { await updateCountry(editId, form); toast.success("Country updated"); }
      else                  { await createCountry(form);         toast.success("Country created"); }
      onClose(); refreshData?.();
    } catch (err: any) { toast.error(err?.message ?? "Failed to save country"); }
    finally { setSaving(false); }
  };

  // Auto-fill flag_url from code
  const handleCodeChange = (e: ChangeEvent<HTMLInputElement>) => {
    const code = e.target.value;
    setForm((p) => ({
      ...p,
      code,
      flag_url: code.trim() ? `https://flagcdn.com/${code.trim().toLowerCase()}.svg` : p.flag_url,
    }));
    setTouched((p) => ({ ...p, code: true }));
    setErrors((p) => ({ ...p, code: "" }));
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modalContent} style={{ maxWidth: "480px" }} onClick={(e) => e.stopPropagation()}>

        {/* Header */}
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>
              {isEdit ? "✏️ Edit Country" : "🌍 New Country"}
            </h2>
            <p className={styles.modalSubtitle}>
              {isEdit ? "Update country details" : "Add a new country"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">✕</button>
        </div>

        {loadingEdit ? (
          <div className={styles.loadingSpinner}>
            <div className={styles.loadingSpinnerIcon} />Loading...
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={styles.form}>
            <div className={styles.formBody}>

              {/* Country Name */}
              <div className={styles.formGroup}>
                <label className={styles.label}>
                  Country Name <span style={{ color: "#ef4444" }}>*</span>
                </label>
                {/* Icon input — mirrors React FaFlag pattern */}
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: "10px", top: "50%", transform: "translateY(-50%)", color: "#8e24aa", pointerEvents: "none" }}>
                    <FaFlag size={13} />
                  </span>
                  <input
                    name="name"
                    value={form.name}
                    onChange={handleChange}
                    placeholder="Enter country name"
                    style={{ paddingLeft: "32px" }}
                    className={`${styles.input} ${showErr("name") ? styles.inputError : ""}`}
                  />
                </div>
                {showErr("name") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.name}</span>}
              </div>

              {/* Country Code */}
              <div className={styles.formGroup} style={{ marginTop: "14px" }}>
                <label className={styles.label}>
                  Country Code <span style={{ color: "#ef4444" }}>*</span>
                </label>
                <input
                  name="code"
                  value={form.code}
                  onChange={handleCodeChange}
                  placeholder="e.g. AE, PK, IN"
                  className={`${styles.input} ${showErr("code") ? styles.inputError : ""}`}
                />
                {showErr("code") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.code}</span>}
              </div>

              {/* Flag URL + preview */}
              <div className={styles.formGroup} style={{ marginTop: "14px" }}>
                <label className={styles.label}>Flag URL</label>
                <div style={{ display: "flex", gap: "10px", alignItems: "center" }}>
                  <input
                    name="flag_url"
                    value={form.flag_url ?? ""}
                    onChange={handleChange}
                    placeholder="https://flagcdn.com/ae.svg"
                    className={styles.input}
                    style={{ flex: 1 }}
                  />
                  {form.flag_url && (
                    <img
                      src={form.flag_url}
                      alt="flag preview"
                      style={{ width: 36, height: 24, objectFit: "cover", borderRadius: 4, border: "1px solid #e5e7eb", flexShrink: 0 }}
                      onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
                    />
                  )}
                </div>
                <span style={{ fontSize: 11, color: "#9ca3af", marginTop: 3 }}>
                  Auto-filled from code. Format: https://flagcdn.com/[code].svg
                </span>
              </div>

            </div>

            <div className={styles.modalFooter}>
              <button type="button" onClick={onClose} className={styles.cancelBtn}>Cancel</button>
              <button type="submit" disabled={saving} className={styles.saveBtn}>
                {saving ? (isEdit ? "Updating…" : "Saving...") : (isEdit ? "Update Country" : "Save Country")}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
