"use client";

import { useState } from "react";

interface Props {
  categories: Record<string, string[]>;
  initialValues: Record<string, string>;
  toggleFields?: string[];
  textareaFields?: string[];
  readonlyFields?: string[];
}

const CATEGORY_ICONS: Record<string, string> = {
  "Site Settings": "M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z",
  "Commission Settings": "M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
  "Registration Settings": "M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z",
  "Content Settings": "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z",
  "Maintenance Mode": "M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z",
  SEO: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z",
  Safety: "M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z",
  Email: "M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z",
  Legal: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z",
};

const CATEGORY_DESCRIPTIONS: Record<string, string> = {
  "Site Settings": "Core site identity and branding configuration",
  "Commission Settings": "Platform fee percentages applied to paid services (set in code constants)",
  "Registration Settings": "Control who can sign up and verification requirements",
  "Content Settings": "Content moderation and upload settings",
  "Maintenance Mode": "Take the site offline for maintenance",
  SEO: "Search engine optimization and analytics tracking",
  Safety: "Age verification and automatic moderation thresholds",
  Email: "SMTP configuration for outgoing emails",
  Legal: "Legal pages and compliance settings",
};

export default function SettingsForm({
  categories,
  initialValues,
  toggleFields = [],
  textareaFields = [],
  readonlyFields = [],
}: Props) {
  const [values, setValues] = useState<Record<string, string>>(initialValues);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  const handleChange = (key: string, value: string) => {
    setValues((prev) => ({ ...prev, [key]: value }));
  };

  const handleToggle = (key: string) => {
    setValues((prev) => ({
      ...prev,
      [key]: prev[key] === "true" ? "false" : "true",
    }));
  };

  const handleSave = async () => {
    setSaving(true);
    setMessage(null);
    try {
      // Filter out readonly fields
      const settings = Object.entries(values)
        .filter(([key]) => !readonlyFields.includes(key))
        .map(([key, value]) => ({ key, value }));

      const res = await fetch("/api/admin/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ settings }),
      });
      if (res.ok) {
        setMessage("Settings saved successfully.");
      } else {
        const data = await res.json();
        setMessage(data.error || "Failed to save settings.");
      }
    } catch {
      setMessage("Network error.");
    } finally {
      setSaving(false);
    }
  };

  const formatLabel = (key: string) =>
    key
      .replace(/_/g, " ")
      .replace(/\b\w/g, (c) => c.toUpperCase());

  const isMaintenanceOn = values["maintenance_mode"] === "true";

  return (
    <div className="space-y-8">
      {/* Maintenance mode banner */}
      {isMaintenanceOn && (
        <div className="bg-amber-900/30 border border-amber-700 rounded-lg p-4 flex items-center gap-3">
          <svg className="w-6 h-6 text-amber-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
          <div>
            <p className="text-amber-400 font-semibold">Maintenance Mode is Active</p>
            <p className="text-text-muted text-sm">
              The site is currently in maintenance mode. Regular users cannot access the site.
            </p>
          </div>
        </div>
      )}

      {Object.entries(categories).map(([category, keys]) => (
        <div key={category} className="bg-surface rounded-lg p-6">
          <div className="flex items-center gap-3 mb-1">
            {CATEGORY_ICONS[category] && (
              <svg
                className={`w-5 h-5 ${
                  category === "Maintenance Mode" && isMaintenanceOn
                    ? "text-amber-400"
                    : "text-primary"
                }`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1.5}
                  d={CATEGORY_ICONS[category]}
                />
              </svg>
            )}
            <h2 className="text-lg font-semibold text-primary">{category}</h2>
          </div>
          {CATEGORY_DESCRIPTIONS[category] && (
            <p className="text-text-muted text-sm mb-4 ml-8">
              {CATEGORY_DESCRIPTIONS[category]}
            </p>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {keys.map((key) => {
              const isToggle = toggleFields.includes(key);
              const isTextarea = textareaFields.includes(key);
              const isReadonly = readonlyFields.includes(key);

              if (isToggle) {
                return (
                  <div key={key} className="flex items-center justify-between col-span-1 md:col-span-2 bg-surface-light rounded-lg px-4 py-3">
                    <div>
                      <p className="text-text text-sm font-medium">{formatLabel(key)}</p>
                      {key === "maintenance_mode" && (
                        <p className="text-text-muted text-xs mt-0.5">
                          When enabled, only admins can access the site
                        </p>
                      )}
                      {key === "allow_new_registrations" && (
                        <p className="text-text-muted text-xs mt-0.5">
                          Allow new users to create accounts
                        </p>
                      )}
                      {key === "require_email_verification" && (
                        <p className="text-text-muted text-xs mt-0.5">
                          Users must verify their email before accessing features
                        </p>
                      )}
                      {key === "nsfw_content_moderation" && (
                        <p className="text-text-muted text-xs mt-0.5">
                          Automatically moderate uploaded content for NSFW violations
                        </p>
                      )}
                      {key === "require_photo_moderation" && (
                        <p className="text-text-muted text-xs mt-0.5">
                          Require manual approval of uploaded photos
                        </p>
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => handleToggle(key)}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                        values[key] === "true" ? "bg-primary" : "bg-surface-light border border-text-muted"
                      }`}
                    >
                      <span
                        className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                          values[key] === "true" ? "translate-x-6" : "translate-x-1"
                        }`}
                      />
                    </button>
                  </div>
                );
              }

              if (isReadonly) {
                return (
                  <div key={key}>
                    <label className="block text-text-muted text-sm mb-1">
                      {formatLabel(key)}
                      <span className="ml-2 text-xs bg-surface-light px-1.5 py-0.5 rounded text-text-muted">
                        Read-only
                      </span>
                    </label>
                    <div className="w-full bg-surface-light/50 border border-surface-light rounded-lg px-4 py-2 text-text-muted">
                      {values[key] ?? ""}%
                    </div>
                    <p className="text-text-muted text-xs mt-1">
                      Set in code constants. Edit <code className="text-primary">src/lib/constants/fees.ts</code> to change.
                    </p>
                  </div>
                );
              }

              if (isTextarea) {
                return (
                  <div key={key} className="col-span-1 md:col-span-2">
                    <label className="block text-text-muted text-sm mb-1">
                      {formatLabel(key)}
                    </label>
                    <textarea
                      value={values[key] ?? ""}
                      onChange={(e) => handleChange(key, e.target.value)}
                      rows={3}
                      className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary resize-y"
                    />
                  </div>
                );
              }

              return (
                <div key={key}>
                  <label className="block text-text-muted text-sm mb-1">
                    {formatLabel(key)}
                  </label>
                  <input
                    type="text"
                    value={values[key] ?? ""}
                    onChange={(e) => handleChange(key, e.target.value)}
                    className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
                  />
                </div>
              );
            })}
          </div>
        </div>
      ))}

      <div className="flex items-center gap-4 bg-surface rounded-lg p-4">
        <button
          onClick={handleSave}
          disabled={saving}
          className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg transition-colors disabled:opacity-50 font-medium"
        >
          {saving ? "Saving..." : "Save All Settings"}
        </button>
        {message && (
          <p
            className={`text-sm ${
              message.includes("success") ? "text-green-400" : "text-red-400"
            }`}
          >
            {message}
          </p>
        )}
      </div>
    </div>
  );
}
