'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { FileText } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';

interface ManualContentPayload {
  title: string;
  subtitle: string;
  quickStart: string[];
  menuMap: { name: string; purpose: string }[];
  sections: { id: string; icon: string; title: string; description: string; steps: string[] }[];
  faq: { q: string; a: string }[];
}

type PendingFocus = { kind: 'menuMap' | 'sections' | 'faq'; index: number };

export default function AdminManualPage() {
  const { token, user } = useAuthStore();
  const { t } = useLanguage();
  const router = useRouter();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [savedSnapshot, setSavedSnapshot] = useState<ManualContentPayload | null>(null);
  const [form, setForm] = useState<ManualContentPayload>({
    title: '',
    subtitle: '',
    quickStart: [],
    menuMap: [],
    sections: [],
    faq: [],
  });

  const toLines = (items: string[]) => items.join('\n');
  // Keep raw line breaks while typing; normalize during save.
  const fromLines = (text: string) => text.split('\n');
  const menuItemRefs = useRef<Array<HTMLDivElement | null>>([]);
  const sectionRefs = useRef<Array<HTMLDivElement | null>>([]);
  const faqRefs = useRef<Array<HTMLDivElement | null>>([]);
  const pendingFocusRef = useRef<PendingFocus | null>(null);

  const focusPendingItem = () => {
    if (!pendingFocusRef.current) return;
    const pendingFocus = pendingFocusRef.current;
    const refsByKind = {
      menuMap: menuItemRefs.current,
      sections: sectionRefs.current,
      faq: faqRefs.current,
    };
    const target = refsByKind[pendingFocus.kind][pendingFocus.index];
    if (!target) return;
    target.scrollIntoView({ behavior: 'smooth', block: 'center' });
    const firstField = target.querySelector('input, textarea') as HTMLElement | null;
    firstField?.focus();
    pendingFocusRef.current = null;
  };

  const queueFocus = (focusTarget: PendingFocus) => {
    pendingFocusRef.current = focusTarget;
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        focusPendingItem();
      });
    });
  };

  useEffect(() => {
    if (!user || user.userType !== 'admin') {
      router.replace('/dashboard');
      return;
    }

    const load = async () => {
      if (!token) return;
      setLoading(true);
      setError('');
      const res = await api.content.getAdminManual(token);
      if (!res.success || !res.data) {
        setError(res.error || t('adminManual.loadFailed'));
        setLoading(false);
        return;
      }
      const data = res.data as ManualContentPayload;
      setForm({
        title: data.title || t('adminManual.defaultTitle'),
        subtitle: data.subtitle || '',
        quickStart: Array.isArray(data.quickStart) ? data.quickStart : [],
        menuMap: Array.isArray(data.menuMap) ? data.menuMap : [],
        sections: Array.isArray(data.sections) ? data.sections : [],
        faq: Array.isArray(data.faq) ? data.faq : [],
      });
      setSavedSnapshot({
        title: data.title || t('adminManual.defaultTitle'),
        subtitle: data.subtitle || '',
        quickStart: Array.isArray(data.quickStart) ? data.quickStart : [],
        menuMap: Array.isArray(data.menuMap) ? data.menuMap : [],
        sections: Array.isArray(data.sections) ? data.sections : [],
        faq: Array.isArray(data.faq) ? data.faq : [],
      });
      setLoading(false);
    };

    void load();
  }, [token, user, router, t]);

  const handleSave = async () => {
    if (!token) return;

    setError('');
    setSuccess('');

    if (!form.title.trim() || !form.subtitle.trim()) {
      setError(t('adminManual.requiredFields'));
      return;
    }

    const payload: ManualContentPayload = {
      title: form.title.trim(),
      subtitle: form.subtitle.trim(),
      quickStart: form.quickStart.map((item) => item.trim()).filter(Boolean),
      menuMap: form.menuMap
        .map((item) => ({ name: item.name.trim(), purpose: item.purpose.trim() }))
        .filter((item) => item.name && item.purpose),
      sections: form.sections
        .map((section) => ({
          id: section.id.trim(),
          icon: section.icon.trim() || 'FileText',
          title: section.title.trim(),
          description: section.description.trim(),
          steps: section.steps.map((step) => step.trim()).filter(Boolean),
        }))
        .filter((section) => section.id && section.title && section.description),
      faq: form.faq
        .map((item) => ({ q: item.q.trim(), a: item.a.trim() }))
        .filter((item) => item.q && item.a),
    };

    setSaving(true);
    const res = await api.content.updateAdminManual(token, payload);
    if (!res.success) {
      setError(res.error || t('adminManual.saveFailed'));
      setSaving(false);
      return;
    }
    const data = res.data as ManualContentPayload;
    setForm({
      title: data.title || payload.title,
      subtitle: data.subtitle || payload.subtitle,
      quickStart: Array.isArray(data.quickStart) ? data.quickStart : payload.quickStart,
      menuMap: Array.isArray(data.menuMap) ? data.menuMap : payload.menuMap,
      sections: Array.isArray(data.sections) ? data.sections : payload.sections,
      faq: Array.isArray(data.faq) ? data.faq : payload.faq,
    });
    setSavedSnapshot({
      title: data.title || payload.title,
      subtitle: data.subtitle || payload.subtitle,
      quickStart: Array.isArray(data.quickStart) ? data.quickStart : payload.quickStart,
      menuMap: Array.isArray(data.menuMap) ? data.menuMap : payload.menuMap,
      sections: Array.isArray(data.sections) ? data.sections : payload.sections,
      faq: Array.isArray(data.faq) ? data.faq : payload.faq,
    });
    setSuccess(t('adminManual.saved'));
    setSaving(false);
  };

  const handleCancel = () => {
    if (!savedSnapshot) return;
    setForm(savedSnapshot);
    setError('');
    setSuccess('');
  };

  if (!user || user.userType !== 'admin') return null;

  return (
    <div className="space-y-6">
      <div className="rounded-2xl border border-cyan-100 bg-linear-to-r from-cyan-50 via-white to-blue-50 p-6 shadow-sm">
        <div className="flex items-center gap-3">
          <div className="rounded-lg bg-white p-2 text-cyan-600 shadow-sm">
            <FileText className="h-5 w-5" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-slate-900">{t('adminManual.title')}</h1>
            <p className="text-sm text-slate-600">{t('adminManual.description')}</p>
          </div>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{t('adminManual.contentTitle')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {loading ? (
            <p className="text-sm text-slate-600">{t('common.loading')}</p>
          ) : (
            <>
              <div className="space-y-2">
                <Label htmlFor="manual-title">{t('adminManual.form.titleLabel')}</Label>
                <Input
                  id="manual-title"
                  value={form.title}
                  onChange={(e) => setForm((prev) => ({ ...prev, title: e.target.value }))}
                  placeholder={t('adminManual.form.titlePlaceholder')}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="manual-subtitle">{t('adminManual.form.subtitleLabel')}</Label>
                <textarea
                  id="manual-subtitle"
                  value={form.subtitle}
                  onChange={(e) => setForm((prev) => ({ ...prev, subtitle: e.target.value }))}
                  className="min-h-20 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-500"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="manual-quickstart">{t('adminManual.form.quickStartLabel')}</Label>
                <textarea
                  id="manual-quickstart"
                  value={toLines(form.quickStart)}
                  onChange={(e) => setForm((prev) => ({ ...prev, quickStart: fromLines(e.target.value) }))}
                  className="min-h-32 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-500"
                />
              </div>

              <div className="space-y-3 rounded-lg border border-slate-200 p-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-slate-900">{t('adminManual.form.menuMapTitle')}</h3>
                  <Button
                    type="button"
                    className="bg-blue-600 text-white hover:bg-blue-500"
                    onClick={() => {
                      const nextIndex = form.menuMap.length;
                      setForm((prev) => ({
                        ...prev,
                        menuMap: [...prev.menuMap, { name: '', purpose: '' }],
                      }));
                      queueFocus({ kind: 'menuMap', index: nextIndex });
                    }}
                  >
                    {t('adminManual.form.addItem')}
                  </Button>
                </div>
                {form.menuMap.map((item, index) => (
                  <div
                    key={`menu-${index}`}
                    ref={(el) => {
                      menuItemRefs.current[index] = el;
                    }}
                    className="grid gap-2 rounded-md border border-slate-200 p-3 md:grid-cols-[1fr_2fr_auto]"
                  >
                    <Input
                      value={item.name}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          menuMap: prev.menuMap.map((current, i) => (i === index ? { ...current, name: e.target.value } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.menuNamePlaceholder')}
                    />
                    <Input
                      value={item.purpose}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          menuMap: prev.menuMap.map((current, i) => (i === index ? { ...current, purpose: e.target.value } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.descriptionPlaceholder')}
                    />
                    <Button
                      type="button"
                      className="bg-red-600 text-white hover:bg-red-500"
                      onClick={() =>
                        setForm((prev) => ({
                          ...prev,
                          menuMap: prev.menuMap.filter((_, i) => i !== index),
                        }))
                      }
                    >
                      {t('adminManual.form.remove')}
                    </Button>
                  </div>
                ))}
              </div>

              <div className="space-y-3 rounded-lg border border-slate-200 p-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-slate-900">{t('adminManual.form.sectionsTitle')}</h3>
                  <Button
                    type="button"
                    className="bg-blue-600 text-white hover:bg-blue-500"
                    onClick={() => {
                      const nextIndex = form.sections.length;
                      setForm((prev) => ({
                        ...prev,
                        sections: [
                          ...prev.sections,
                          { id: '', icon: 'FileText', title: '', description: '', steps: [] },
                        ],
                      }));
                      queueFocus({ kind: 'sections', index: nextIndex });
                    }}
                  >
                    {t('adminManual.form.addSection')}
                  </Button>
                </div>
                {form.sections.map((section, index) => (
                  <div
                    key={`section-${index}`}
                    ref={(el) => {
                      sectionRefs.current[index] = el;
                    }}
                    className="space-y-2 rounded-md border border-slate-200 p-3"
                  >
                    <div className="grid gap-2 md:grid-cols-3">
                      <Input
                        value={section.id}
                        onChange={(e) =>
                          setForm((prev) => ({
                            ...prev,
                            sections: prev.sections.map((current, i) => (i === index ? { ...current, id: e.target.value } : current)),
                          }))
                        }
                        placeholder="id"
                      />
                      <Input
                        value={section.icon}
                        onChange={(e) =>
                          setForm((prev) => ({
                            ...prev,
                            sections: prev.sections.map((current, i) => (i === index ? { ...current, icon: e.target.value } : current)),
                          }))
                        }
                        placeholder={t('adminManual.form.iconPlaceholder')}
                      />
                      <Button
                        type="button"
                        className="bg-red-600 text-white hover:bg-red-500"
                        onClick={() =>
                          setForm((prev) => ({
                            ...prev,
                            sections: prev.sections.filter((_, i) => i !== index),
                          }))
                        }
                      >
                        {t('adminManual.form.remove')}
                      </Button>
                    </div>
                    <Input
                      value={section.title}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          sections: prev.sections.map((current, i) => (i === index ? { ...current, title: e.target.value } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.sectionTitlePlaceholder')}
                    />
                    <textarea
                      value={section.description}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          sections: prev.sections.map((current, i) => (i === index ? { ...current, description: e.target.value } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.descriptionPlaceholder')}
                      className="min-h-20 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-500"
                    />
                    <textarea
                      value={toLines(section.steps)}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          sections: prev.sections.map((current, i) => (i === index ? { ...current, steps: fromLines(e.target.value) } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.stepsPlaceholder')}
                      className="min-h-24 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-500"
                    />
                  </div>
                ))}
              </div>

              <div className="space-y-3 rounded-lg border border-slate-200 p-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-slate-900">{t('adminManual.form.faqTitle')}</h3>
                  <Button
                    type="button"
                    className="bg-blue-600 text-white hover:bg-blue-500"
                    onClick={() => {
                      const nextIndex = form.faq.length;
                      setForm((prev) => ({
                        ...prev,
                        faq: [...prev.faq, { q: '', a: '' }],
                      }));
                      queueFocus({ kind: 'faq', index: nextIndex });
                    }}
                  >
                    {t('adminManual.form.addFaq')}
                  </Button>
                </div>
                {form.faq.map((item, index) => (
                  <div
                    key={`faq-${index}`}
                    ref={(el) => {
                      faqRefs.current[index] = el;
                    }}
                    className="space-y-2 rounded-md border border-slate-200 p-3"
                  >
                    <Input
                      value={item.q}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          faq: prev.faq.map((current, i) => (i === index ? { ...current, q: e.target.value } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.questionPlaceholder')}
                    />
                    <textarea
                      value={item.a}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          faq: prev.faq.map((current, i) => (i === index ? { ...current, a: e.target.value } : current)),
                        }))
                      }
                      placeholder={t('adminManual.form.answerPlaceholder')}
                      className="min-h-20 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-500"
                    />
                    <div className="flex justify-end">
                      <Button
                        type="button"
                        className="bg-red-600 text-white hover:bg-red-500"
                        onClick={() =>
                          setForm((prev) => ({
                            ...prev,
                            faq: prev.faq.filter((_, i) => i !== index),
                          }))
                        }
                      >
                        {t('adminManual.form.remove')}
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {error ? <p className="text-sm font-medium text-red-600">{error}</p> : null}
          {success ? <p className="text-sm font-medium text-green-700">{success}</p> : null}

          <div className="flex justify-end gap-2">
            <Button onClick={handleCancel} disabled={loading || saving || !savedSnapshot} className="bg-orange-500 text-white hover:bg-orange-400">
              {t('common.cancel')}
            </Button>
            <Button onClick={handleSave} disabled={loading || saving} className="bg-green-600 text-white hover:bg-green-500">
              {saving ? t('common.saving') : t('adminManual.saveButton')}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
