'use client';

import { useEffect, useState } from 'react';
import { apiFetchJson } from '@/lib/auth';

interface WebsiteContent {
  hero: {
    title: string;
    subtitle: string;
    ctaText: string;
    ctaSecondaryText: string;
    heroImageUrl: string;
  };
  features: Array<{ title: string; description: string; icon?: string }>;
  faq: Array<{ question: string; answer: string }>;
  footer: {
    email: string;
    phone: string;
    address: string;
    linkedinUrl: string;
    twitterUrl: string;
    instagramUrl: string;
    copyrightText: string;
  };
}

type TabKey = 'hero' | 'features' | 'faq' | 'footer';

const TABS: { key: TabKey; label: string; icon: JSX.Element }[] = [
  {
    key: 'hero',
    label: 'Ana Banner',
    icon: (
      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h7" />
      </svg>
    ),
  },
  {
    key: 'features',
    label: 'Özellikler',
    icon: (
      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
      </svg>
    ),
  },
  {
    key: 'faq',
    label: 'SSS',
    icon: (
      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    ),
  },
  {
    key: 'footer',
    label: 'Footer',
    icon: (
      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
      </svg>
    ),
  },
];

export default function WebsitePage() {
  const [content, setContent] = useState<WebsiteContent | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<TabKey>('hero');
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);

  // Local editable state
  const [heroForm, setHeroForm] = useState({ title: '', subtitle: '', ctaText: '', ctaSecondaryText: '', heroImageUrl: '' });
  const [footerForm, setFooterForm] = useState({ email: '', phone: '', address: '', linkedinUrl: '', twitterUrl: '', instagramUrl: '', copyrightText: '' });
  const [features, setFeatures] = useState<Array<{ title: string; description: string }>>([]);
  const [faq, setFaq] = useState<Array<{ question: string; answer: string }>>([]);

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 3500);
  };

  useEffect(() => {
    apiFetchJson<WebsiteContent>('/v1/platform/website').then((res) => {
      if (res.error === null && res.data) {
        setContent(res.data);
        setHeroForm(res.data.hero);
        setFooterForm(res.data.footer);
        setFeatures(res.data.features ?? []);
        setFaq(res.data.faq ?? []);
      }
      setLoading(false);
    });
  }, []);

  const handleSave = async () => {
    let section = activeTab;
    let data: unknown;
    if (activeTab === 'hero') data = heroForm;
    else if (activeTab === 'footer') data = footerForm;
    else if (activeTab === 'features') data = features;
    else if (activeTab === 'faq') data = faq;

    setSaving(true);
    try {
      const res = await apiFetchJson(`/v1/platform/website/${section}`, {
        method: 'PATCH',
        body: JSON.stringify(data),
      });
      if (res.error === null) {
        showToast('Değişiklikler kaydedildi');
      } else {
        showToast(res.error || 'Hata oluştu', 'error');
      }
    } finally {
      setSaving(false);
    }
  };

  const inputCls = 'w-full rounded-xl border border-slate-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent';
  const labelCls = 'block text-xs font-semibold text-slate-600 uppercase tracking-wide mb-1.5';

  return (
    <div className="space-y-8">
      {/* Toast */}
      {toast && (
        <div className={`fixed top-5 right-5 z-50 rounded-xl px-5 py-3.5 text-sm font-medium shadow-xl ${toast.type === 'success' ? 'bg-emerald-600 text-white' : 'bg-red-600 text-white'}`}>
          {toast.msg}
        </div>
      )}

      {/* Page header */}
      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-slate-900 via-teal-950 to-slate-900 px-8 py-10 text-white shadow-xl">
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute -top-16 -right-16 h-56 w-56 rounded-full bg-teal-500/10 blur-3xl" />
        </div>
        <div className="relative flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 text-teal-300 text-sm font-medium mb-2">
              <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
              </svg>
              Website CMS
            </div>
            <h1 className="text-3xl font-bold tracking-tight">Website İçerik Yönetimi</h1>
            <p className="mt-1.5 text-slate-300">Lansman sayfasının içeriklerini düzenleyin.</p>
          </div>
          <button
            onClick={handleSave}
            disabled={saving || loading}
            className="flex items-center gap-2 rounded-xl bg-white/10 hover:bg-white/20 backdrop-blur-sm px-4 py-2.5 text-sm font-semibold text-white border border-white/20 disabled:opacity-50 transition-colors"
          >
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
            </svg>
            {saving ? 'Kaydediliyor...' : 'Kaydet'}
          </button>
        </div>
      </div>

      {/* Tabs + content */}
      <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
        {/* Tab bar */}
        <div className="flex border-b border-slate-100 px-4 pt-4">
          {TABS.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium rounded-t-lg border-b-2 mr-1 transition-colors ${
                activeTab === tab.key
                  ? 'border-indigo-600 text-indigo-700 bg-indigo-50/50'
                  : 'border-transparent text-slate-500 hover:text-slate-700'
              }`}
            >
              {tab.icon}
              {tab.label}
            </button>
          ))}
        </div>

        {loading ? (
          <div className="p-8 space-y-4">
            {Array.from({ length: 5 }).map((_, i) => <div key={i} className="h-12 rounded-xl bg-slate-100 animate-pulse" />)}
          </div>
        ) : (
          <div className="p-8">
            {/* Hero tab */}
            {activeTab === 'hero' && (
              <div className="space-y-5 max-w-2xl">
                <div>
                  <label className={labelCls}>Başlık</label>
                  <input value={heroForm.title} onChange={(e) => setHeroForm({ ...heroForm, title: e.target.value })} className={inputCls} />
                </div>
                <div>
                  <label className={labelCls}>Alt Başlık</label>
                  <textarea
                    value={heroForm.subtitle}
                    onChange={(e) => setHeroForm({ ...heroForm, subtitle: e.target.value })}
                    rows={3}
                    className={inputCls + ' resize-none'}
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={labelCls}>Birincil CTA Metni</label>
                    <input value={heroForm.ctaText} onChange={(e) => setHeroForm({ ...heroForm, ctaText: e.target.value })} className={inputCls} />
                  </div>
                  <div>
                    <label className={labelCls}>İkincil CTA Metni</label>
                    <input value={heroForm.ctaSecondaryText} onChange={(e) => setHeroForm({ ...heroForm, ctaSecondaryText: e.target.value })} className={inputCls} />
                  </div>
                </div>
                <div>
                  <label className={labelCls}>Hero Görsel URL</label>
                  <input value={heroForm.heroImageUrl} onChange={(e) => setHeroForm({ ...heroForm, heroImageUrl: e.target.value })} placeholder="https://..." className={inputCls} />
                </div>
                {/* Preview */}
                <div className="mt-6 rounded-xl bg-gradient-to-br from-indigo-50 to-violet-50 border border-indigo-100 p-6">
                  <div className="text-xs font-semibold text-indigo-400 uppercase tracking-wide mb-3">Önizleme</div>
                  <h2 className="text-2xl font-bold text-slate-900">{heroForm.title || 'Başlık'}</h2>
                  <p className="text-slate-600 mt-2">{heroForm.subtitle || 'Alt başlık...'}</p>
                  <div className="flex gap-3 mt-4">
                    <span className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white">{heroForm.ctaText || 'CTA'}</span>
                    <span className="rounded-lg border border-indigo-300 px-4 py-2 text-sm font-semibold text-indigo-700">{heroForm.ctaSecondaryText || 'İkincil CTA'}</span>
                  </div>
                </div>
              </div>
            )}

            {/* Features tab */}
            {activeTab === 'features' && (
              <div className="space-y-4 max-w-2xl">
                <div className="flex items-center justify-between">
                  <p className="text-sm text-slate-500">Lansman sayfasındaki özellik kartları</p>
                  <button
                    onClick={() => setFeatures([...features, { title: '', description: '' }])}
                    className="flex items-center gap-1.5 rounded-lg bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition-colors"
                  >
                    <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                    </svg>
                    Özellik Ekle
                  </button>
                </div>
                {features.length === 0 && (
                  <div className="py-10 text-center rounded-xl border border-dashed border-slate-300 text-slate-400 text-sm">
                    Henüz özellik eklenmedi
                  </div>
                )}
                {features.map((f, i) => (
                  <div key={i} className="rounded-xl border border-slate-200 p-4 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-semibold text-slate-500">Özellik #{i + 1}</span>
                      <button
                        onClick={() => setFeatures(features.filter((_, j) => j !== i))}
                        className="text-slate-400 hover:text-red-500 transition-colors"
                      >
                        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </button>
                    </div>
                    <div>
                      <label className={labelCls}>Başlık</label>
                      <input
                        value={f.title}
                        onChange={(e) => setFeatures(features.map((x, j) => j === i ? { ...x, title: e.target.value } : x))}
                        className={inputCls}
                      />
                    </div>
                    <div>
                      <label className={labelCls}>Açıklama</label>
                      <textarea
                        value={f.description}
                        onChange={(e) => setFeatures(features.map((x, j) => j === i ? { ...x, description: e.target.value } : x))}
                        rows={2}
                        className={inputCls + ' resize-none'}
                      />
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* FAQ tab */}
            {activeTab === 'faq' && (
              <div className="space-y-4 max-w-2xl">
                <div className="flex items-center justify-between">
                  <p className="text-sm text-slate-500">Sık sorulan sorular bölümü</p>
                  <button
                    onClick={() => setFaq([...faq, { question: '', answer: '' }])}
                    className="flex items-center gap-1.5 rounded-lg bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition-colors"
                  >
                    <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                    </svg>
                    Soru Ekle
                  </button>
                </div>
                {faq.length === 0 && (
                  <div className="py-10 text-center rounded-xl border border-dashed border-slate-300 text-slate-400 text-sm">
                    Henüz SSS eklenmedi
                  </div>
                )}
                {faq.map((item, i) => (
                  <div key={i} className="rounded-xl border border-slate-200 p-4 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-semibold text-slate-500">Soru #{i + 1}</span>
                      <button
                        onClick={() => setFaq(faq.filter((_, j) => j !== i))}
                        className="text-slate-400 hover:text-red-500 transition-colors"
                      >
                        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </button>
                    </div>
                    <div>
                      <label className={labelCls}>Soru</label>
                      <input
                        value={item.question}
                        onChange={(e) => setFaq(faq.map((x, j) => j === i ? { ...x, question: e.target.value } : x))}
                        className={inputCls}
                      />
                    </div>
                    <div>
                      <label className={labelCls}>Cevap</label>
                      <textarea
                        value={item.answer}
                        onChange={(e) => setFaq(faq.map((x, j) => j === i ? { ...x, answer: e.target.value } : x))}
                        rows={3}
                        className={inputCls + ' resize-none'}
                      />
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Footer tab */}
            {activeTab === 'footer' && (
              <div className="space-y-5 max-w-2xl">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={labelCls}>E-posta</label>
                    <input value={footerForm.email} onChange={(e) => setFooterForm({ ...footerForm, email: e.target.value })} type="email" className={inputCls} />
                  </div>
                  <div>
                    <label className={labelCls}>Telefon</label>
                    <input value={footerForm.phone} onChange={(e) => setFooterForm({ ...footerForm, phone: e.target.value })} className={inputCls} />
                  </div>
                </div>
                <div>
                  <label className={labelCls}>Adres</label>
                  <textarea value={footerForm.address} onChange={(e) => setFooterForm({ ...footerForm, address: e.target.value })} rows={2} className={inputCls + ' resize-none'} />
                </div>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <label className={labelCls}>LinkedIn URL</label>
                    <input value={footerForm.linkedinUrl} onChange={(e) => setFooterForm({ ...footerForm, linkedinUrl: e.target.value })} placeholder="https://..." className={inputCls} />
                  </div>
                  <div>
                    <label className={labelCls}>Twitter URL</label>
                    <input value={footerForm.twitterUrl} onChange={(e) => setFooterForm({ ...footerForm, twitterUrl: e.target.value })} placeholder="https://..." className={inputCls} />
                  </div>
                  <div>
                    <label className={labelCls}>Instagram URL</label>
                    <input value={footerForm.instagramUrl} onChange={(e) => setFooterForm({ ...footerForm, instagramUrl: e.target.value })} placeholder="https://..." className={inputCls} />
                  </div>
                </div>
                <div>
                  <label className={labelCls}>Telif Hakkı Metni</label>
                  <input value={footerForm.copyrightText} onChange={(e) => setFooterForm({ ...footerForm, copyrightText: e.target.value })} className={inputCls} />
                </div>
              </div>
            )}
          </div>
        )}

        {/* Save footer */}
        <div className="px-8 py-4 border-t border-slate-100 bg-slate-50/50 flex items-center justify-between">
          <p className="text-xs text-slate-400">Değişiklikler kaydedildiğinde anında yayına alınır.</p>
          <button
            onClick={handleSave}
            disabled={saving || loading}
            className="flex items-center gap-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-60 transition-colors shadow-sm"
          >
            {saving ? (
              <>
                <svg className="h-4 w-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Kaydediliyor...
              </>
            ) : (
              <>
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                </svg>
                Değişiklikleri Kaydet
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
