﻿// react
import React, { useEffect, useState } from "react";
// application
import { IFooterSettings, IFooterSocialLink } from "~/admin/interfaces/footerSettings";

const SOCIAL_TYPES: { value: string; label: string; icon: string }[] = [
  { value: "facebook", label: "Facebook", icon: "fab fa-facebook-f" },
  { value: "instagram", label: "Instagram", icon: "fab fa-instagram" },
  { value: "youtube", label: "YouTube", icon: "fab fa-youtube" },
  { value: "tiktok", label: "TikTok", icon: "fab fa-tiktok" },
  { value: "linkedin", label: "LinkedIn", icon: "fab fa-linkedin-in" },
  { value: "twitter", label: "Twitter / X", icon: "fab fa-twitter" },
  { value: "whatsapp", label: "WhatsApp", icon: "fab fa-whatsapp" },
];

interface Props {
  initial: IFooterSettings;
  onSave: (data: IFooterSettings) => Promise<void>;
  saving: boolean;
}

function iconForType(type: string): string {
  const row = SOCIAL_TYPES.find((s) => s.value === type);
  return row ? row.icon : "fas fa-link";
}

function StringListEditor(props: {
  label: string;
  values: string[];
  onChange: (next: string[]) => void;
  placeholder?: string;
}) {
  const { label, values, onChange, placeholder } = props;
  const updateAt = (i: number, v: string) => {
    const next = [...values];
    next[i] = v;
    onChange(next);
  };
  const add = () => onChange([...values, ""]);
  const remove = (i: number) => onChange(values.filter((_, idx) => idx !== i));

  return (
    <div className="mb-4">
      <label className="font-weight-bold d-block mb-2">{label}</label>
      {values.map((v, i) => (
        <div key={i} className="input-group mb-2">
          <input
            type="text"
            className="form-control"
            value={v}
            placeholder={placeholder}
            onChange={(e) => updateAt(i, e.target.value)}
          />
          <div className="input-group-append">
            <button type="button" className="btn btn-outline-danger" onClick={() => remove(i)}>
              <i className="fas fa-times" />
            </button>
          </div>
        </div>
      ))}
      <button type="button" className="btn btn-sm btn-outline-primary" onClick={add}>
        <i className="fas fa-plus mr-1" /> Agregar
      </button>
    </div>
  );
}

export function FooterSettingsForm({ initial, onSave, saving }: Props) {
  const [form, setForm] = useState<IFooterSettings>(initial);

  useEffect(() => {
    setForm(initial);
  }, [initial]);

  const setSocial = (links: IFooterSocialLink[]) =>
    setForm((f) => ({ ...f, socialLinks: links }));

  const updateSocial = (i: number, patch: Partial<IFooterSocialLink>) => {
    const links = [...form.socialLinks];
    const cur = { ...links[i], ...patch };
    if (patch.type !== undefined) {
      cur.icon = iconForType(cur.type);
    }
    links[i] = cur;
    setSocial(links);
  };

  const addSocial = () =>
    setSocial([...form.socialLinks, { type: "youtube", url: "", icon: iconForType("youtube") }]);

  const removeSocial = (i: number) =>
    setSocial(form.socialLinks.filter((_, idx) => idx !== i));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const payload: IFooterSettings = {
      ...form,
      socialLinks: form.socialLinks.map((l) => ({
        ...l,
        icon: iconForType(l.type),
      })),
    };
    await onSave(payload);
  };

  return (
    <form onSubmit={handleSubmit} className="card">
      <div className="card-body">
        <h4 className="card-title mb-4">Contáctenos</h4>

        <div className="form-group">
          <label>Título</label>
          <input
            type="text"
            className="form-control"
            value={form.contactTitle}
            onChange={(e) => setForm({ ...form, contactTitle: e.target.value })}
          />
        </div>
        <div className="form-group">
          <label>Subtítulo</label>
          <textarea
            className="form-control"
            rows={3}
            value={form.contactSubtitle}
            onChange={(e) => setForm({ ...form, contactSubtitle: e.target.value })}
          />
        </div>

        <div className="row">
          <div className="col-md-6 form-group">
            <label>Etiqueta teléfonos</label>
            <input
              type="text"
              className="form-control"
              value={form.labelPhone}
              onChange={(e) => setForm({ ...form, labelPhone: e.target.value })}
            />
          </div>
          <div className="col-md-6 form-group">
            <label>Etiqueta correos</label>
            <input
              type="text"
              className="form-control"
              value={form.labelEmail}
              onChange={(e) => setForm({ ...form, labelEmail: e.target.value })}
            />
          </div>
          <div className="col-md-6 form-group">
            <label>Etiqueta ubicaciones</label>
            <input
              type="text"
              className="form-control"
              value={form.labelAddress}
              onChange={(e) => setForm({ ...form, labelAddress: e.target.value })}
            />
          </div>
          <div className="col-md-6 form-group">
            <label>Etiqueta horarios</label>
            <input
              type="text"
              className="form-control"
              value={form.labelHours}
              onChange={(e) => setForm({ ...form, labelHours: e.target.value })}
            />
          </div>
        </div>

        <StringListEditor
          label="Números de teléfono"
          values={form.phones}
          onChange={(phones) => setForm({ ...form, phones })}
          placeholder="+58 ..."
        />
        <StringListEditor
          label="Correos electrónicos"
          values={form.emails}
          onChange={(emails) => setForm({ ...form, emails })}
          placeholder="correo@ejemplo.com"
        />
        <StringListEditor
          label="Ubicaciones"
          values={form.addresses}
          onChange={(addresses) => setForm({ ...form, addresses })}
        />
        <StringListEditor
          label="Horarios"
          values={form.hours}
          onChange={(hours) => setForm({ ...form, hours })}
          placeholder="Lunes a viernes..."
        />

        <hr className="my-4" />
        <h4 className="card-title mb-3">Redes sociales (footer)</h4>
        <div className="form-group">
          <label>Título de la sección (opcional)</label>
          <input
            type="text"
            className="form-control"
            value={form.socialSectionTitle}
            onChange={(e) => setForm({ ...form, socialSectionTitle: e.target.value })}
            placeholder="Si lo dejas vacío, el sitio usará el texto traducido por defecto"
          />
        </div>

        {form.socialLinks.map((link, i) => (
          <div key={i} className="border rounded p-3 mb-3">
            <div className="form-row">
              <div className="form-group col-md-4">
                <label>Red</label>
                <select
                  className="form-control"
                  value={link.type}
                  onChange={(e) => updateSocial(i, { type: e.target.value })}
                >
                  {SOCIAL_TYPES.map((s) => (
                    <option key={s.value} value={s.value}>
                      {s.label}
                    </option>
                  ))}
                </select>
              </div>
              <div className="form-group col-md-6">
                <label>URL</label>
                <input
                  type="url"
                  className="form-control"
                  value={link.url}
                  onChange={(e) => updateSocial(i, { url: e.target.value })}
                  placeholder="https://"
                />
              </div>
              <div className="form-group col-md-2 d-flex align-items-end">
                <button
                  type="button"
                  className="btn btn-outline-danger btn-block"
                  onClick={() => removeSocial(i)}
                >
                  <i className="fas fa-trash" />
                </button>
              </div>
            </div>
          </div>
        ))}
        <button type="button" className="btn btn-outline-primary mb-4" onClick={addSocial}>
          <i className="fas fa-plus mr-1" /> Agregar red social
        </button>

        <div>
          <button type="submit" className="btn btn-primary" disabled={saving}>
            {saving ? (
              <>
                <span className="spinner-border spinner-border-sm mr-2" role="status" />
                Guardando…
              </>
            ) : (
              <>
                <i className="fas fa-save mr-2" /> Guardar cambios
              </>
            )}
          </button>
        </div>
      </div>
    </form>
  );
}
