'use client';

import { useCallback, useEffect, useState } from 'react';
import {
  landingAdminApi,
  type LandingResponse,
  type LandingStat,
  type LandingServiceCard,
} from '@/lib/api';

type LandingSubTab = 'hero' | 'stats' | 'services-block' | 'service-cards' | 'contact';

export default function LandingAdmin() {
  const [subTab, setSubTab] = useState<LandingSubTab>('hero');
  const [data, setData] = useState<LandingResponse | null>(null);
  const [stats, setStats] = useState<LandingStat[]>([]);
  const [serviceCards, setServiceCards] = useState<LandingServiceCard[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const loadAll = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [landing, statsList, cardsList] = await Promise.all([
        landingAdminApi.get(),
        landingAdminApi.getStats(),
        landingAdminApi.getServiceCards(),
      ]);
      setData(landing);
      setStats(statsList);
      setServiceCards(cardsList);
    } catch (err: any) {
      setError(err?.response?.data?.detail || err?.message || 'Failed to load landing data');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const showMsg = (msg: string) => {
    setMessage(msg);
    setTimeout(() => setMessage(null), 4000);
  };

  const subTabs: { id: LandingSubTab; label: string }[] = [
    { id: 'hero', label: 'Hero' },
    { id: 'stats', label: 'Stats' },
    { id: 'services-block', label: 'Services block' },
    { id: 'service-cards', label: 'Service cards' },
    { id: 'contact', label: 'Contact' },
  ];

  if (loading && !data) {
    return <div className="landing-admin-loading">Loading landing content…</div>;
  }

  return (
    <div className="landing-admin">
      <div className="landing-admin-header">
        <h2>Landing page content</h2>
        <a href="/" target="_blank" rel="noopener noreferrer" className="landing-admin-view-link">
          View landing page ↗
        </a>
      </div>
      {error && <div className="landing-admin-error">{error}</div>}
      {message && <div className="landing-admin-message">{message}</div>}
      <div className="landing-admin-tabs">
        {subTabs.map((t) => (
          <button
            key={t.id}
            type="button"
            className={`landing-admin-tab ${subTab === t.id ? 'active' : ''}`}
            onClick={() => setSubTab(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>
      <div className="landing-admin-content">
        {subTab === 'hero' && data && (
          <HeroForm initial={data.hero} onSave={async (d) => { await landingAdminApi.putHero(d); showMsg('Hero saved'); loadAll(); }} />
        )}
        {subTab === 'stats' && (
          <StatsCrud stats={stats} onRefresh={loadAll} onMessage={showMsg} />
        )}
        {subTab === 'services-block' && data && (
          <ServicesBlockForm initial={data.services_block} onSave={async (d) => { await landingAdminApi.putServicesBlock(d); showMsg('Services block saved'); loadAll(); }} />
        )}
        {subTab === 'service-cards' && (
          <ServiceCardsCrud cards={serviceCards} onRefresh={loadAll} onMessage={showMsg} />
        )}
        {subTab === 'contact' && data && (
          <ContactForm initial={data.contact} onSave={async (d) => { await landingAdminApi.putContact(d); showMsg('Contact saved'); loadAll(); }} />
        )}
      </div>
    </div>
  );
}

function HeroForm({
  initial,
  onSave,
}: {
  initial: LandingResponse['hero'];
  onSave: (d: { title?: string; subtitle?: string; banner_text?: string; background_image_url?: string }) => Promise<void>;
}) {
  const [title, setTitle] = useState(initial.title);
  const [subtitle, setSubtitle] = useState(initial.subtitle);
  const [banner_text, setBannerText] = useState(initial.banner_text || '');
  const [background_image_url, setBackgroundImageUrl] = useState(initial.background_image_url || '');
  const [saving, setSaving] = useState(false);
  useEffect(() => {
    setTitle(initial.title);
    setSubtitle(initial.subtitle);
    setBannerText(initial.banner_text || '');
    setBackgroundImageUrl(initial.background_image_url || '');
  }, [initial]);
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await onSave({ title, subtitle, banner_text: banner_text || undefined, background_image_url: background_image_url || undefined });
    } finally {
      setSaving(false);
    }
  };
  return (
    <form onSubmit={handleSubmit} className="landing-admin-form">
      <label>Title <input value={title} onChange={(e) => setTitle(e.target.value)} required /></label>
      <label>Subtitle <input value={subtitle} onChange={(e) => setSubtitle(e.target.value)} required /></label>
      <label>Banner text <input value={banner_text} onChange={(e) => setBannerText(e.target.value)} /></label>
      <label>Background image URL <input type="url" value={background_image_url} onChange={(e) => setBackgroundImageUrl(e.target.value)} /></label>
      <button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save hero'}</button>
    </form>
  );
}

function StatsCrud({
  stats,
  onRefresh,
  onMessage,
}: { stats: LandingStat[]; onRefresh: () => void; onMessage: (m: string) => void }) {
  const [adding, setAdding] = useState(false);
  const [label, setLabel] = useState('');
  const [value, setValue] = useState('');
  const [sort_order, setSortOrder] = useState(0);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editLabel, setEditLabel] = useState('');
  const [editValue, setEditValue] = useState('');
  const [editSortOrder, setEditSortOrder] = useState(0);
  const [submitting, setSubmitting] = useState(false);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!label.trim() || !value.trim()) return;
    setSubmitting(true);
    try {
      await landingAdminApi.postStat({ label: label.trim(), value: value.trim(), sort_order });
      onMessage('Stat added');
      setLabel('');
      setValue('');
      setSortOrder(0);
      onRefresh();
    } catch (err: any) {
      onMessage(err?.response?.data?.detail || 'Failed to add');
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = (s: LandingStat) => {
    setEditingId(s.id);
    setEditLabel(s.label);
    setEditValue(s.value);
    setEditSortOrder(s.sort_order);
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (editingId == null) return;
    setSubmitting(true);
    try {
      await landingAdminApi.putStat(editingId, { label: editLabel, value: editValue, sort_order: editSortOrder });
      onMessage('Stat updated');
      setEditingId(null);
      onRefresh();
    } catch (err: any) {
      onMessage(err?.response?.data?.detail || 'Failed to update');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Delete this stat?')) return;
    try {
      await landingAdminApi.deleteStat(id);
      onMessage('Stat deleted');
      if (editingId === id) setEditingId(null);
      onRefresh();
    } catch (err: any) {
      onMessage(err?.response?.data?.detail || 'Failed to delete');
    }
  };

  return (
    <div className="landing-admin-stats">
      <form onSubmit={handleAdd} className="landing-admin-form landing-admin-form-inline">
        <input placeholder="Label" value={label} onChange={(e) => setLabel(e.target.value)} />
        <input placeholder="Value" value={value} onChange={(e) => setValue(e.target.value)} />
        <input type="number" placeholder="Order" value={sort_order} onChange={(e) => setSortOrder(Number(e.target.value))} />
        <button type="submit" disabled={submitting}>Add stat</button>
      </form>
      {editingId != null && (
        <form onSubmit={handleUpdate} className="landing-admin-form landing-admin-form-inline">
          <input value={editLabel} onChange={(e) => setEditLabel(e.target.value)} />
          <input value={editValue} onChange={(e) => setEditValue(e.target.value)} />
          <input type="number" value={editSortOrder} onChange={(e) => setEditSortOrder(Number(e.target.value))} />
          <button type="submit" disabled={submitting}>Update</button>
          <button type="button" onClick={() => setEditingId(null)}>Cancel</button>
        </form>
      )}
      <ul className="landing-admin-list">
        {stats.map((s) => (
          <li key={s.id}>
            <span>{s.label}: {s.value}</span>
            <span>
              <button type="button" onClick={() => handleEdit(s)}>Edit</button>
              <button type="button" onClick={() => handleDelete(s.id)}>Delete</button>
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ServicesBlockForm({
  initial,
  onSave,
}: {
  initial: LandingResponse['services_block'];
  onSave: (d: Partial<LandingResponse['services_block']>) => Promise<void>;
}) {
  const [title, setTitle] = useState(initial.title);
  const [body_text, setBodyText] = useState(initial.body_text || '');
  const [image_url, setImageUrl] = useState(initial.image_url || '');
  const [b1_label, setB1Label] = useState(initial.button_1_label || '');
  const [b1_url, setB1Url] = useState(initial.button_1_url || '');
  const [b2_label, setB2Label] = useState(initial.button_2_label || '');
  const [b2_url, setB2Url] = useState(initial.button_2_url || '');
  const [b3_label, setB3Label] = useState(initial.button_3_label || '');
  const [b3_url, setB3Url] = useState(initial.button_3_url || '');
  const [saving, setSaving] = useState(false);
  useEffect(() => {
    setTitle(initial.title);
    setBodyText(initial.body_text || '');
    setImageUrl(initial.image_url || '');
    setB1Label(initial.button_1_label || '');
    setB1Url(initial.button_1_url || '');
    setB2Label(initial.button_2_label || '');
    setB2Url(initial.button_2_url || '');
    setB3Label(initial.button_3_label || '');
    setB3Url(initial.button_3_url || '');
  }, [initial]);
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await onSave({
        title,
        body_text: body_text || undefined,
        image_url: image_url || undefined,
        button_1_label: b1_label || undefined,
        button_1_url: b1_url || undefined,
        button_2_label: b2_label || undefined,
        button_2_url: b2_url || undefined,
        button_3_label: b3_label || undefined,
        button_3_url: b3_url || undefined,
      });
    } finally {
      setSaving(false);
    }
  };
  return (
    <form onSubmit={handleSubmit} className="landing-admin-form">
      <label>Title <input value={title} onChange={(e) => setTitle(e.target.value)} required /></label>
      <label>Body <textarea value={body_text} onChange={(e) => setBodyText(e.target.value)} rows={3} /></label>
      <label>Image URL <input type="url" value={image_url} onChange={(e) => setImageUrl(e.target.value)} /></label>
      <label>Button 1 label <input value={b1_label} onChange={(e) => setB1Label(e.target.value)} /></label>
      <label>Button 1 URL <input value={b1_url} onChange={(e) => setB1Url(e.target.value)} /></label>
      <label>Button 2 label <input value={b2_label} onChange={(e) => setB2Label(e.target.value)} /></label>
      <label>Button 2 URL <input value={b2_url} onChange={(e) => setB2Url(e.target.value)} /></label>
      <label>Button 3 label <input value={b3_label} onChange={(e) => setB3Label(e.target.value)} /></label>
      <label>Button 3 URL <input value={b3_url} onChange={(e) => setB3Url(e.target.value)} /></label>
      <button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save services block'}</button>
    </form>
  );
}

function ServiceCardsCrud({
  cards,
  onRefresh,
  onMessage,
}: { cards: LandingServiceCard[]; onRefresh: () => void; onMessage: (m: string) => void }) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [link_url, setLinkUrl] = useState('');
  const [sort_order, setSortOrder] = useState(0);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editTitle, setEditTitle] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [editLinkUrl, setEditLinkUrl] = useState('');
  const [editSortOrder, setEditSortOrder] = useState(0);
  const [submitting, setSubmitting] = useState(false);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) return;
    setSubmitting(true);
    try {
      await landingAdminApi.postServiceCard({ title: title.trim(), description: description || undefined, link_url: link_url || undefined, sort_order });
      onMessage('Service card added');
      setTitle('');
      setDescription('');
      setLinkUrl('');
      setSortOrder(0);
      onRefresh();
    } catch (err: any) {
      onMessage(err?.response?.data?.detail || 'Failed to add');
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = (c: LandingServiceCard) => {
    setEditingId(c.id);
    setEditTitle(c.title);
    setEditDescription(c.description || '');
    setEditLinkUrl(c.link_url || '');
    setEditSortOrder(c.sort_order);
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (editingId == null) return;
    setSubmitting(true);
    try {
      await landingAdminApi.putServiceCard(editingId, { title: editTitle, description: editDescription, link_url: editLinkUrl || undefined, sort_order: editSortOrder });
      onMessage('Service card updated');
      setEditingId(null);
      onRefresh();
    } catch (err: any) {
      onMessage(err?.response?.data?.detail || 'Failed to update');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Delete this service card?')) return;
    try {
      await landingAdminApi.deleteServiceCard(id);
      onMessage('Service card deleted');
      if (editingId === id) setEditingId(null);
      onRefresh();
    } catch (err: any) {
      onMessage(err?.response?.data?.detail || 'Failed to delete');
    }
  };

  return (
    <div className="landing-admin-cards">
      <form onSubmit={handleAdd} className="landing-admin-form">
        <label>Title <input value={title} onChange={(e) => setTitle(e.target.value)} required /></label>
        <label>Description <textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={2} /></label>
        <label>Link URL <input value={link_url} onChange={(e) => setLinkUrl(e.target.value)} /></label>
        <label>Sort order <input type="number" value={sort_order} onChange={(e) => setSortOrder(Number(e.target.value))} /></label>
        <button type="submit" disabled={submitting}>Add card</button>
      </form>
      {editingId != null && (
        <form onSubmit={handleUpdate} className="landing-admin-form">
          <label>Title <input value={editTitle} onChange={(e) => setEditTitle(e.target.value)} /></label>
          <label>Description <textarea value={editDescription} onChange={(e) => setEditDescription(e.target.value)} rows={2} /></label>
          <label>Link URL <input value={editLinkUrl} onChange={(e) => setEditLinkUrl(e.target.value)} /></label>
          <label>Sort order <input type="number" value={editSortOrder} onChange={(e) => setEditSortOrder(Number(e.target.value))} /></label>
          <button type="submit" disabled={submitting}>Update</button>
          <button type="button" onClick={() => setEditingId(null)}>Cancel</button>
        </form>
      )}
      <ul className="landing-admin-list">
        {cards.map((c) => (
          <li key={c.id}>
            <span>{c.title}</span>
            <span>
              <button type="button" onClick={() => handleEdit(c)}>Edit</button>
              <button type="button" onClick={() => handleDelete(c.id)}>Delete</button>
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ContactForm({
  initial,
  onSave,
}: {
  initial: LandingResponse['contact'];
  onSave: (d: { phone?: string; email?: string; address?: string }) => Promise<void>;
}) {
  const [phone, setPhone] = useState(initial.phone || '');
  const [email, setEmail] = useState(initial.email || '');
  const [address, setAddress] = useState(initial.address || '');
  const [saving, setSaving] = useState(false);
  useEffect(() => {
    setPhone(initial.phone || '');
    setEmail(initial.email || '');
    setAddress(initial.address || '');
  }, [initial]);
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await onSave({ phone: phone || undefined, email: email || undefined, address: address || undefined });
    } finally {
      setSaving(false);
    }
  };
  return (
    <form onSubmit={handleSubmit} className="landing-admin-form">
      <label>Phone <input value={phone} onChange={(e) => setPhone(e.target.value)} /></label>
      <label>Email <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /></label>
      <label>Address <textarea value={address} onChange={(e) => setAddress(e.target.value)} rows={2} /></label>
      <button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save contact'}</button>
    </form>
  );
}
