import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { Skeleton } from "@libs/skeleton";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import {
  GripVertical,
  Plus,
  Trash2,
  ChevronDown,
  ChevronUp,
  ToggleLeft,
  ToggleRight,
} from "lucide-react";

const FIELD_TYPES = [
  { value: "text", label: __("Text", "arraysubs") },
  { value: "textarea", label: __("Textarea", "arraysubs") },
  { value: "select", label: __("Select", "arraysubs") },
  { value: "date", label: __("Date", "arraysubs") },
  { value: "checkbox", label: __("Checkbox", "arraysubs") },
  { value: "upload", label: __("File Upload", "arraysubs") },
];

const getApiConfig = () => {
  const { env } = window.arraySubs || {};
  return {
    apiBaseUrl: `${env?.apiBaseUrl || ""}arraysubs/v1`,
    nonce: env?.nonce || "",
  };
};

const generateKey = (label) => {
  if (!label) return "";
  return label
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_|_$/g, "")
    .substring(0, 40);
};

/**
 * Single field editor row
 */
const FieldEditor = ({ field, index, onChange, onRemove, onMove, total }) => {
  const [expanded, setExpanded] = useState(false);

  const update = (key, value) => {
    onChange(index, { ...field, [key]: value });
  };

  const updateMultiple = (updates) => {
    onChange(index, { ...field, ...updates });
  };

  const updateOption = (optIndex, key, value) => {
    const options = [...(field.options || [])];
    options[optIndex] = { ...options[optIndex], [key]: value };
    update("options", options);
  };

  const addOption = () => {
    const options = [...(field.options || []), { value: "", label: "" }];
    update("options", options);
  };

  const removeOption = (optIndex) => {
    const options = (field.options || []).filter((_, i) => i !== optIndex);
    update("options", options);
  };

  return (
    <div
      className={`arraysubs-field-editor ${
        !field.enabled ? "arraysubs-field-editor--disabled" : ""
      }`}
    >
      <div className="arraysubs-field-editor__header">
        <span className="arraysubs-field-editor__drag">
          <GripVertical size={16} />
        </span>

        <span className="arraysubs-field-editor__label">
          {field.label || __("Untitled Field", "arraysubs")}
        </span>

        <span className="arraysubs-field-editor__type-badge">
          {FIELD_TYPES.find((t) => t.value === field.type)?.label || field.type}
        </span>

        <span className="arraysubs-field-editor__actions">
          <button
            type="button"
            className="arraysubs-field-editor__toggle-btn"
            onClick={() => update("enabled", !field.enabled)}
            title={
              field.enabled
                ? __("Disable field", "arraysubs")
                : __("Enable field", "arraysubs")
            }
          >
            {field.enabled ? (
              <ToggleRight size={20} color="#2271b1" />
            ) : (
              <ToggleLeft size={20} color="#999" />
            )}
          </button>

          <button
            type="button"
            className="arraysubs-field-editor__move-btn"
            disabled={index === 0}
            onClick={() => onMove(index, index - 1)}
            title={__("Move up", "arraysubs")}
          >
            <ChevronUp size={16} />
          </button>

          <button
            type="button"
            className="arraysubs-field-editor__move-btn"
            disabled={index === total - 1}
            onClick={() => onMove(index, index + 1)}
            title={__("Move down", "arraysubs")}
          >
            <ChevronDown size={16} />
          </button>

          <button
            type="button"
            className="arraysubs-field-editor__expand-btn"
            onClick={() => setExpanded(!expanded)}
          >
            {expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </button>

          <button
            type="button"
            className="arraysubs-field-editor__remove-btn"
            onClick={() => onRemove(index)}
            title={__("Remove field", "arraysubs")}
          >
            <Trash2 size={16} />
          </button>
        </span>
      </div>

      {expanded && (
        <div className="arraysubs-field-editor__body">
          <div className="arraysubs-field-editor__row">
            <div className="arraysubs-field-editor__col">
              <label>{__("Label", "arraysubs")}</label>
              <input
                type="text"
                value={field.label || ""}
                onChange={(e) => {
                  const updates = { label: e.target.value };
                  if (!field._keyEdited) {
                    updates.key = generateKey(e.target.value);
                  }
                  updateMultiple(updates);
                }}
                placeholder={__("Field label", "arraysubs")}
                className="regular-text"
              />
            </div>
            <div className="arraysubs-field-editor__col">
              <label>{__("Key", "arraysubs")}</label>
              <input
                type="text"
                value={field.key || ""}
                onChange={(e) => {
                  updateMultiple({
                    key: e.target.value.replace(/[^a-z0-9_]/g, ""),
                    _keyEdited: true,
                  });
                }}
                placeholder={__("field_key", "arraysubs")}
                className="regular-text"
              />
              <span className="arraysubs-field-editor__hint">
                {__("Stored as user meta: arraysubs_pf_{key}", "arraysubs")}
              </span>
            </div>
          </div>

          <div className="arraysubs-field-editor__row">
            <div className="arraysubs-field-editor__col">
              <label>{__("Type", "arraysubs")}</label>
              <select
                value={field.type || "text"}
                onChange={(e) => update("type", e.target.value)}
              >
                {FIELD_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))}
              </select>
            </div>
            <div className="arraysubs-field-editor__col">
              <label>{__("Placeholder / Description", "arraysubs")}</label>
              <input
                type="text"
                value={field.placeholder || ""}
                onChange={(e) => update("placeholder", e.target.value)}
                placeholder={__("Placeholder text", "arraysubs")}
                className="regular-text"
              />
            </div>
          </div>

          <div className="arraysubs-field-editor__row">
            <div className="arraysubs-field-editor__col">
              <label>{__("Help Text", "arraysubs")}</label>
              <input
                type="text"
                value={field.help_text || ""}
                onChange={(e) => update("help_text", e.target.value)}
                placeholder={__(
                  "Optional help text shown below field",
                  "arraysubs",
                )}
                className="regular-text"
              />
            </div>
            <div className="arraysubs-field-editor__col arraysubs-field-editor__col--checkbox">
              <label>
                <input
                  type="checkbox"
                  checked={!!field.required}
                  onChange={(e) => update("required", e.target.checked)}
                />
                {__("Required", "arraysubs")}
              </label>
            </div>
          </div>

          {field.type === "select" && (
            <div className="arraysubs-field-editor__options">
              <label>{__("Options", "arraysubs")}</label>
              {(field.options || []).map((opt, optIdx) => (
                <div
                  key={optIdx}
                  className="arraysubs-field-editor__option-row"
                >
                  <input
                    type="text"
                    value={opt.value || ""}
                    onChange={(e) =>
                      updateOption(optIdx, "value", e.target.value)
                    }
                    placeholder={__("Value", "arraysubs")}
                  />
                  <input
                    type="text"
                    value={opt.label || ""}
                    onChange={(e) =>
                      updateOption(optIdx, "label", e.target.value)
                    }
                    placeholder={__("Label", "arraysubs")}
                  />
                  <button
                    type="button"
                    className="button arraysubs-field-editor__option-remove"
                    onClick={() => removeOption(optIdx)}
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              ))}
              <button type="button" className="button" onClick={addOption}>
                <Plus size={14} /> {__("Add Option", "arraysubs")}
              </button>
            </div>
          )}

          {field.type === "upload" && (
            <div className="arraysubs-field-editor__row">
              <div className="arraysubs-field-editor__col">
                <label>{__("Allowed File Types", "arraysubs")}</label>
                <input
                  type="text"
                  value={(field.allowed_types || []).join(", ")}
                  onChange={(e) =>
                    update(
                      "allowed_types",
                      e.target.value
                        .split(",")
                        .map((t) => t.trim().toLowerCase())
                        .filter(Boolean),
                    )
                  }
                  placeholder="jpg, jpeg, png, pdf"
                  className="regular-text"
                />
                <span className="arraysubs-field-editor__hint">
                  {__("Comma-separated extensions", "arraysubs")}
                </span>
              </div>
              <div className="arraysubs-field-editor__col">
                <label>{__("Max File Size (MB)", "arraysubs")}</label>
                <input
                  type="number"
                  min="1"
                  max="100"
                  value={field.max_file_size || 5}
                  onChange={(e) =>
                    update("max_file_size", parseInt(e.target.value, 10) || 5)
                  }
                />
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

/**
 * Profile Fields Settings Page
 */
const ProfileFieldsSettings = () => {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [fields, setFields] = useState([]);
  const [customFieldsEnabled, setCustomFieldsEnabled] = useState(true);
  const [avatarSettings, setAvatarSettings] = useState({
    enabled: false,
    max_file_size: 2,
    allowed_types: ["jpg", "jpeg", "png", "gif", "webp"],
  });
  const { toasts, showToast, removeToast } = useToast();

  const loadConfig = useCallback(async () => {
    setLoading(true);
    const { apiBaseUrl, nonce } = getApiConfig();

    try {
      const response = await fetch(`${apiBaseUrl}/profile-fields/config`, {
        headers: { "X-WP-Nonce": nonce },
      });
      const data = await response.json();

      if (data.content) {
        setFields(data.content.fields || []);
        setCustomFieldsEnabled(
          data.content.custom_profile_fields_enabled ?? true,
        );
        setAvatarSettings(
          data.content.avatar_settings || {
            enabled: false,
            max_file_size: 2,
            allowed_types: ["jpg", "jpeg", "png", "gif", "webp"],
          },
        );
      }
    } catch (err) {
      showToast(
        err.message || __("Failed to load configuration", "arraysubs"),
        "error",
      );
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadConfig();
  }, [loadConfig]);

  const handleSave = async () => {
    if (customFieldsEnabled) {
      const invalidFields = fields.filter((f) => !f.key || !f.label);
      if (invalidFields.length > 0) {
        showToast(
          __("All fields must have a key and label.", "arraysubs"),
          "error",
        );
        return;
      }

      const keys = fields.map((f) => f.key);
      const uniqueKeys = new Set(keys);
      if (keys.length !== uniqueKeys.size) {
        showToast(__("Field keys must be unique.", "arraysubs"), "error");
        return;
      }
    }

    setSaving(true);
    const { apiBaseUrl, nonce } = getApiConfig();

    try {
      const cleanedFields = fields.map((f, idx) => {
        const cleaned = { ...f, position: idx };
        delete cleaned._keyEdited;
        return cleaned;
      });

      const response = await fetch(`${apiBaseUrl}/profile-fields/config`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": nonce,
        },
        body: JSON.stringify({
          fields: cleanedFields,
          avatar_settings: avatarSettings,
          custom_profile_fields_enabled: customFieldsEnabled,
        }),
      });

      const data = await response.json();

      if (response.ok && data.content) {
        setFields(data.content.fields || []);
        setCustomFieldsEnabled(
          data.content.custom_profile_fields_enabled ?? customFieldsEnabled,
        );
        setAvatarSettings(data.content.avatar_settings || avatarSettings);
        showToast(__("Configuration saved!", "arraysubs"), "success");
      } else {
        showToast(
          data.message || __("Failed to save configuration", "arraysubs"),
          "error",
        );
      }
    } catch (err) {
      showToast(
        err.message || __("Failed to save configuration", "arraysubs"),
        "error",
      );
    } finally {
      setSaving(false);
    }
  };

  const addField = () => {
    setFields([
      ...fields,
      {
        key: "",
        label: "",
        type: "text",
        required: false,
        placeholder: "",
        help_text: "",
        enabled: true,
        position: fields.length,
      },
    ]);
  };

  const updateField = (index, updatedField) => {
    const updated = [...fields];
    updated[index] = updatedField;
    setFields(updated);
  };

  const removeField = (index) => {
    setFields(fields.filter((_, i) => i !== index));
  };

  const moveField = (from, to) => {
    if (to < 0 || to >= fields.length) return;
    const updated = [...fields];
    const [moved] = updated.splice(from, 1);
    updated.splice(to, 0, moved);
    setFields(updated);
  };

  if (loading) {
    return (
      <DefaultPageLayout title={__("Profile Fields", "arraysubs")}>
        <Skeleton variant="rectangle" width="100%" height={400} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Profile Fields", "arraysubs")}
      subtitle={__(
        "Configure extra profile fields and avatar for customer accounts",
        "arraysubs",
      )}
    >
      {/* Avatar Settings */}
      <div className="arraysubs-card">
        <h3 className="arraysubs-card__title">
          {__("Avatar Settings", "arraysubs")}
        </h3>
        <p className="arraysubs-card__description">
          {__(
            "Allow customers to upload a profile photo from their Account Details page.",
            "arraysubs",
          )}
        </p>

        <div className="arraysubs-pf-avatar-settings">
          <label className="arraysubs-pf-avatar-settings__toggle">
            <input
              type="checkbox"
              checked={avatarSettings.enabled}
              onChange={(e) =>
                setAvatarSettings({
                  ...avatarSettings,
                  enabled: e.target.checked,
                })
              }
            />
            {__("Enable avatar upload", "arraysubs")}
          </label>

          {avatarSettings.enabled && (
            <div className="arraysubs-pf-avatar-settings__options">
              <div className="arraysubs-pf-avatar-settings__row">
                <label>{__("Max File Size (MB)", "arraysubs")}</label>
                <input
                  type="number"
                  min="1"
                  max="20"
                  value={avatarSettings.max_file_size}
                  onChange={(e) =>
                    setAvatarSettings({
                      ...avatarSettings,
                      max_file_size: parseInt(e.target.value, 10) || 2,
                    })
                  }
                />
              </div>
              <div className="arraysubs-pf-avatar-settings__row">
                <label>{__("Allowed File Types", "arraysubs")}</label>
                <input
                  type="text"
                  value={avatarSettings.allowed_types.join(", ")}
                  onChange={(e) =>
                    setAvatarSettings({
                      ...avatarSettings,
                      allowed_types: e.target.value
                        .split(",")
                        .map((t) => t.trim().toLowerCase())
                        .filter(Boolean),
                    })
                  }
                  placeholder="jpg, jpeg, png, gif, webp"
                  className="regular-text"
                />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Profile Fields */}
      <div className="arraysubs-card">
        <h3 className="arraysubs-card__title">
          {__("Custom Profile Fields", "arraysubs")}
        </h3>
        <p className="arraysubs-card__description">
          {__(
            "Define extra fields that appear on the WooCommerce Account Details page and in the WP Admin user profile.",
            "arraysubs",
          )}
        </p>

        <label className="arraysubs-pf-avatar-settings__toggle">
          <input
            type="checkbox"
            checked={customFieldsEnabled}
            onChange={(e) => setCustomFieldsEnabled(e.target.checked)}
          />
          {__("Enable custom profile fields", "arraysubs")}
        </label>

        {!customFieldsEnabled ? (
          <div className="arraysubs-pf-empty">
            <p>
              {__(
                "Custom profile fields are currently disabled. Your saved field configuration is kept and will be applied again when you re-enable this toggle.",
                "arraysubs",
              )}
            </p>
          </div>
        ) : fields.length === 0 ? (
          <div className="arraysubs-pf-empty">
            <p>
              {__(
                "No custom profile fields defined yet. Click the button below to add your first field.",
                "arraysubs",
              )}
            </p>
          </div>
        ) : (
          <div className="arraysubs-pf-fields-list">
            {fields.map((field, index) => (
              <FieldEditor
                key={`${field.key || "new"}-${index}`}
                field={field}
                index={index}
                onChange={updateField}
                onRemove={removeField}
                onMove={moveField}
                total={fields.length}
              />
            ))}
          </div>
        )}

        {customFieldsEnabled && (
          <button
            type="button"
            className="button arraysubs-pf-add-btn"
            onClick={addField}
          >
            <Plus size={16} /> {__("Add Field", "arraysubs")}
          </button>
        )}
      </div>

      {/* Save Actions */}
      <div className="arraysubs-settings-actions arraysubs-bottom-fixed-actions">
        <div>
          <button
            type="button"
            className="button button-primary"
            onClick={handleSave}
            disabled={saving}
          >
            {saving
              ? __("Saving...", "arraysubs")
              : __("Save Configuration", "arraysubs")}
          </button>
        </div>
      </div>

      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </DefaultPageLayout>
  );
};

export default ProfileFieldsSettings;
