"use client";

import { useState, useEffect, useRef } from "react";

interface Setting {
  id: string;
  key: string;
  value: string | null;
  type: string;
  group: string | null;
}

interface SubSection {
  title: string;
  keys: string[];
}

const settingGroups: Array<{
  label: string;
  description: string;
  keys?: string[];
  subSections?: SubSection[];
}> = [
  {
    label: "Informasi Umum",
    description: "Nama perusahaan dan logo",
    keys: ["company_name", "site_logo"],
  },
  {
    label: "Kontak",
    description: "Informasi kontak perusahaan",
    keys: ["company_phone", "company_email", "company_address_id", "company_address_en", "whatsapp_number"],
  },
  {
    label: "Social Media",
    description: "URL media sosial perusahaan",
    keys: ["facebook_url", "instagram_url", "linkedin_url", "twitter_url"],
  },
  {
    label: "Beranda - Hero",
    description: "Bagian utama halaman beranda",
    keys: ["hero_badge", "hero_title", "hero_description"],
  },
  {
    label: "Beranda - Statistik",
    description: "Angka statistik yang ditampilkan",
    keys: ["stats_1_number", "stats_1_label", "stats_2_number", "stats_2_label", "stats_3_number", "stats_3_label", "stats_4_number", "stats_4_label"],
  },
  {
    label: "Beranda - Mengapa Kami",
    description: "Alasan memilih perusahaan anda",
    keys: ["why_title", "why_description", "why_item1_title", "why_item1_desc", "why_item2_title", "why_item2_desc", "why_item3_title", "why_item3_desc", "why_item4_title", "why_item4_desc"],
  },
  {
    label: "Beranda - CTA",
    description: "Call to action di bagian bawah beranda",
    keys: ["cta_title", "cta_description", "cta_whatsapp", "cta_phone"],
  },
  {
    label: "Footer",
    description: "Pengaturan footer website",
    keys: ["footer_description", "footer_copyright"],
  },
  {
    label: "Google Maps",
    description: "Embed URL Google Maps untuk halaman kontak",
    keys: ["google_maps_embed"],
  },
  {
    label: "Halaman",
    description: "Pengaturan hero dan konten semua halaman",
    subSections: [
      {
        title: "Hero - Layanan",
        keys: ["layanan_hero_title", "layanan_hero_description"],
      },
      {
        title: "Hero - Portofolio",
        keys: ["portofolio_hero_title", "portofolio_hero_description"],
      },
      {
        title: "Hero - Blog",
        keys: ["blog_hero_title", "blog_hero_description"],
      },
      {
        title: "Hero - Kontak",
        keys: ["kontak_hero_title", "kontak_hero_description"],
      },
      {
        title: "Hero - Tentang Kami",
        keys: ["about_hero_title", "about_hero_description"],
      },
      {
        title: "Tentang Kami - Profil",
        keys: ["about_profile_p1", "about_profile_p2", "about_profile_p3"],
      },
      {
        title: "Tentang Kami - Nilai",
        keys: [
          "about_value1_title", "about_value1_desc",
          "about_value2_title", "about_value2_desc",
          "about_value3_title", "about_value3_desc",
          "about_value4_title", "about_value4_desc",
        ],
      },
      {
        title: "Tentang Kami - Tim",
        keys: [
          "about_team1_name", "about_team1_role", "about_team1_desc", "about_team1_photo",
          "about_team2_name", "about_team2_role", "about_team2_desc", "about_team2_photo",
          "about_team3_name", "about_team3_role", "about_team3_desc", "about_team3_photo",
        ],
      },
    ],
  },
];

function formatLabel(key: string): string {
  const labels: Record<string, string> = {
    company_name: "Nama Perusahaan",
    site_logo: "Logo Perusahaan",
    company_phone: "Telepon",
    company_email: "Email",
    company_address_id: "Alamat (Indonesia)",
    company_address_en: "Alamat (English)",
    whatsapp_number: "Nomor WhatsApp",
    facebook_url: "Facebook URL",
    instagram_url: "Instagram URL",
    linkedin_url: "LinkedIn URL",
    twitter_url: "Twitter URL",
    hero_badge: "Badge Teks",
    hero_title: "Judul Hero",
    hero_description: "Deskripsi Hero",
    stats_1_number: "Statistik 1 Angka",
    stats_1_label: "Statistik 1 Label",
    stats_2_number: "Statistik 2 Angka",
    stats_2_label: "Statistik 2 Label",
    stats_3_number: "Statistik 3 Angka",
    stats_3_label: "Statistik 3 Label",
    stats_4_number: "Statistik 4 Angka",
    stats_4_label: "Statistik 4 Label",
    why_title: "Judul",
    why_description: "Deskripsi",
    why_item1_title: "Item 1 Judul",
    why_item1_desc: "Item 1 Deskripsi",
    why_item2_title: "Item 2 Judul",
    why_item2_desc: "Item 2 Deskripsi",
    why_item3_title: "Item 3 Judul",
    why_item3_desc: "Item 3 Deskripsi",
    why_item4_title: "Item 4 Judul",
    why_item4_desc: "Item 4 Deskripsi",
    cta_title: "Judul CTA",
    cta_description: "Deskripsi CTA",
    cta_whatsapp: "WhatsApp Link",
    cta_phone: "Nomor Telepon",
    footer_description: "Deskripsi Footer",
    footer_copyright: "Hak Cipta",
    google_maps_embed: "Google Maps Embed URL",
    layanan_hero_title: "Judul Hero",
    layanan_hero_description: "Deskripsi Hero",
    portofolio_hero_title: "Judul Hero",
    portofolio_hero_description: "Deskripsi Hero",
    blog_hero_title: "Judul Hero",
    blog_hero_description: "Deskripsi Hero",
    kontak_hero_title: "Judul Hero",
    kontak_hero_description: "Deskripsi Hero",
    about_hero_title: "Judul Hero",
    about_hero_description: "Deskripsi Hero",
    about_profile_p1: "Paragraf 1",
    about_profile_p2: "Paragraf 2",
    about_profile_p3: "Paragraf 3",
    about_value1_title: "Nilai 1 Judul",
    about_value1_desc: "Nilai 1 Deskripsi",
    about_value2_title: "Nilai 2 Judul",
    about_value2_desc: "Nilai 2 Deskripsi",
    about_value3_title: "Nilai 3 Judul",
    about_value3_desc: "Nilai 3 Deskripsi",
    about_value4_title: "Nilai 4 Judul",
    about_value4_desc: "Nilai 4 Deskripsi",
    about_team1_name: "Tim 1 Nama",
    about_team1_role: "Tim 1 Role",
    about_team1_desc: "Tim 1 Deskripsi",
    about_team1_photo: "Tim 1 Foto",
    about_team2_name: "Tim 2 Nama",
    about_team2_role: "Tim 2 Role",
    about_team2_desc: "Tim 2 Deskripsi",
    about_team2_photo: "Tim 2 Foto",
    about_team3_name: "Tim 3 Nama",
    about_team3_role: "Tim 3 Role",
    about_team3_desc: "Tim 3 Deskripsi",
    about_team3_photo: "Tim 3 Foto",
  };
  return labels[key] || key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

function getInputType(key: string): "text" | "url" | "tel" | "textarea" {
  if (key.includes("description") || key.includes("desc") || key === "footer_description" || key.endsWith("_p1") || key.endsWith("_p2") || key.endsWith("_p3")) return "textarea";
  if (key.includes("url") || key === "google_maps_embed") return "url";
  if (key.includes("phone") || key.includes("number") || key === "whatsapp_number" || key === "cta_phone") return "tel";
  return "text";
}

function TeamPhotoUpload({ value, onChange }: { value: string; onChange: (url: string) => void }) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    setError("");
    setUploading(true);

    const formData = new FormData();
    formData.append("file", file);
    formData.append("type", "team_photo");

    try {
      const res = await fetch("/api/admin/upload", { method: "POST", body: formData });
      const data = await res.json();
      if (res.ok) {
        onChange(data.url);
      } else {
        setError(data.error || "Gagal upload");
      }
    } catch {
      setError("Gagal upload file");
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }

  return (
    <div className="space-y-2">
      {value && (
        <div className="flex items-center gap-3">
          <img src={value} alt="Foto tim" className="w-16 h-16 object-cover rounded-full border border-gray-200" />
          <button
            type="button"
            onClick={() => onChange("")}
            className="text-sm text-red-500 hover:text-red-700"
          >
            Hapus
          </button>
        </div>
      )}
      <input
        ref={inputRef}
        type="file"
        accept="image/png,image/jpeg,image/jpg"
        onChange={handleUpload}
        className="w-full text-sm text-gray-500 file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-brand-blue/10 file:text-brand-blue hover:file:bg-brand-blue/20 cursor-pointer"
      />
      {error && <p className="text-red-500 text-sm">{error}</p>}
    </div>
  );
}

function LogoUpload({ value, onChange }: { value: string; onChange: (url: string) => void }) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    setError("");
    setUploading(true);

    const formData = new FormData();
    formData.append("file", file);

    try {
      const res = await fetch("/api/admin/upload", { method: "POST", body: formData });
      const data = await res.json();
      if (res.ok) {
        onChange(data.url);
      } else {
        setError(data.error || "Gagal upload");
      }
    } catch {
      setError("Gagal upload file");
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }

  return (
    <div className="space-y-3">
      {value && (
        <div className="flex items-center gap-4">
          <img src={value} alt="Logo" className="h-16 w-auto bg-gray-100 rounded-lg p-2" />
          <button
            type="button"
            onClick={() => onChange("")}
            className="text-sm text-red-500 hover:text-red-700"
          >
            Hapus Logo
          </button>
        </div>
      )}
      <div className="flex items-center gap-3">
        <input
          ref={inputRef}
          type="file"
          accept="image/png,image/jpeg,image/jpg"
          onChange={handleUpload}
          className="hidden"
          id="logo-upload"
        />
        <label
          htmlFor="logo-upload"
          className="inline-flex items-center px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors cursor-pointer text-sm font-medium"
        >
          {uploading ? "Mengupload..." : "Pilih File (PNG/JPG, max 2MB)"}
        </label>
      </div>
      {error && <p className="text-red-500 text-sm">{error}</p>}
    </div>
  );
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<Setting[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState(settingGroups[0].label);

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

  async function fetchSettings() {
    const res = await fetch("/api/admin/settings");
    const data = await res.json();
    setSettings(data);
    setLoading(false);
  }

  function getValue(key: string): string {
    return settings.find((s) => s.key === key)?.value || "";
  }

  function setValue(key: string, value: string) {
    setSettings((prev) => {
      const existing = prev.find((s) => s.key === key);
      if (existing) {
        return prev.map((s) => (s.key === key ? { ...s, value } : s));
      }
      return [...prev, { id: "", key, value, type: "text", group: null }];
    });
  }

  async function handleSave() {
    setSaving(true);
    const data: Record<string, string> = {};
    settings.forEach((s) => {
      if (s.key) data[s.key] = s.value || "";
    });

    await fetch("/api/admin/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });

    setSaving(false);
    alert("Pengaturan tersimpan!");
  }

  if (loading) {
    return <div className="text-center py-8">Loading...</div>;
  }

  const activeGroup = settingGroups.find((g) => g.label === activeTab) || settingGroups[0];

  function renderField(key: string) {
    const inputType = getInputType(key);

    if (key === "site_logo") {
      return (
        <div key={key}>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            {formatLabel(key)}
          </label>
          <LogoUpload
            value={getValue(key)}
            onChange={(url) => setValue(key, url)}
          />
        </div>
      );
    }

    if (key.endsWith("_photo")) {
      return (
        <div key={key}>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            {formatLabel(key)}
          </label>
          <TeamPhotoUpload
            value={getValue(key)}
            onChange={(url) => setValue(key, url)}
          />
        </div>
      );
    }

    if (inputType === "textarea") {
      return (
        <div key={key}>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            {formatLabel(key)}
          </label>
          <textarea
            value={getValue(key)}
            onChange={(e) => setValue(key, e.target.value)}
            rows={3}
            className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none resize-none"
          />
        </div>
      );
    }

    return (
      <div key={key}>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          {formatLabel(key)}
        </label>
        <input
          type={inputType}
          value={getValue(key)}
          onChange={(e) => setValue(key, e.target.value)}
          placeholder={inputType === "url" ? "https://..." : ""}
          className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none"
        />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">Pengaturan</h1>
          <p className="text-gray-500">Kelola pengaturan website</p>
        </div>
        <button
          onClick={handleSave}
          disabled={saving}
          className="px-6 py-2 bg-brand-blue text-white rounded-lg hover:bg-brand-blue-dark transition-colors disabled:opacity-50"
        >
          {saving ? "Menyimpan..." : "Simpan"}
        </button>
      </div>

      <div className="flex gap-6">
        {/* Sidebar Tabs */}
        <div className="w-56 flex-shrink-0">
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden sticky top-8">
            {settingGroups.map((group) => (
              <button
                key={group.label}
                onClick={() => setActiveTab(group.label)}
                className={`w-full text-left px-4 py-3 text-sm transition-colors ${
                  activeTab === group.label
                    ? "bg-brand-blue text-white font-medium"
                    : "text-gray-600 hover:bg-gray-50"
                }`}
              >
                {group.label}
              </button>
            ))}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1">
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-6">
            <h2 className="text-lg font-semibold text-gray-800 mb-1">{activeGroup.label}</h2>
            {activeGroup.description && (
              <p className="text-sm text-gray-500 mb-6">{activeGroup.description}</p>
            )}

            {/* Flat keys mode */}
            {activeGroup.keys && (
              <div className="space-y-5">
                {activeGroup.keys.map((key) => renderField(key))}
              </div>
            )}

            {/* Sub-sections mode */}
            {activeGroup.subSections && (
              <div className="space-y-8">
                {activeGroup.subSections.map((sub) => (
                  <div key={sub.title}>
                    <h3 className="text-sm font-semibold text-gray-800 uppercase tracking-wider mb-4 pb-2 border-b border-gray-100">
                      {sub.title}
                    </h3>
                    <div className="space-y-4">
                      {sub.keys.map((key) => renderField(key))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
