'use client';
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react';
import { toPng } from 'html-to-image';
import { kg, int, MONTHS, MONTHS_SHORT } from '@/lib/format';

export type VisualData = {
  name: string;
  startDate: string;
  lastDay: string;
  dayNumber: number;
  startWeight: number;
  current: number;
  lost: number;
  remaining: number | null;
  progressPct: number | null;
  goalWeight: number | null;
  goalDate: string | null;
  avgSteps: number | null;
  avgCalories: number | null;
  avgProtein: number | null;
  stepGoal: number | null;
  stepHit: number;
  stepLogged: number;
  before: { url: string; day: string } | null;
  after: { url: string; day: string } | null;
};

type Format = 'post' | 'story';
const SIZES: Record<Format, { w: number; h: number; label: string }> = {
  post: { w: 1080, h: 1350, label: 'Gönderi 1080×1350' },
  story: { w: 1080, h: 1920, label: 'Story 1080×1920' },
};
const ACCENTS = [
  { name: 'Lime', hex: '#C8F031' },
  { name: 'Turuncu', hex: '#FF8A3D' },
  { name: 'Mavi', hex: '#7CC6FF' },
  { name: 'Beyaz', hex: '#F2F2EC' },
];

const up = (s: string) => s.toLocaleUpperCase('tr-TR');
const dParts = (s: string) => {
  const [, m, d] = s.split('-').map(Number);
  return { d, m: m - 1 };
};
const dayLong = (s: string) => {
  const p = dParts(s);
  return `${p.d} ${MONTHS[p.m]}`;
};
const dayShort = (s: string) => {
  const p = dParts(s);
  return `${p.d} ${MONTHS_SHORT[p.m]}`;
};
const yearLong = (s: string) => `${dayLong(s)} ${s.slice(0, 4)}`;

/** İmzalı fotoğraf adresini data URL'e çevirir; PNG dışa aktarımı başka alan adına takılmasın. */
function useDataUrl(url: string | undefined) {
  const [src, setSrc] = useState<string | null>(null);
  useEffect(() => {
    if (!url) return;
    let alive = true;
    fetch(url)
      .then((r) => r.blob())
      .then(
        (b) =>
          new Promise<string>((res, rej) => {
            const fr = new FileReader();
            fr.onload = () => res(String(fr.result));
            fr.onerror = rej;
            fr.readAsDataURL(b);
          }),
      )
      .then((d) => alive && setSrc(d))
      .catch(() => alive && setSrc(url));
    return () => {
      alive = false;
    };
  }, [url]);
  return src;
}

const DISPLAY = "'Barlow Condensed', 'Arial Narrow', sans-serif";
const SANS = 'Inter, system-ui, sans-serif';
const C = { bg: '#121311', fg: '#F2F2EC', muted: '#9A9C93', faint: '#6E7068', line: '#2A2C27', panel: '#1A1B18' };

function Canvas({ data, format, accent, beforeSrc, afterSrc }: { data: VisualData; format: Format; accent: string; beforeSrc: string | null; afterSrc: string | null }) {
  const story = format === 'story';
  const { w, h } = SIZES[format];
  const photoH = story ? 680 : 600;
  const statNum: CSSProperties = { fontFamily: DISPLAY, fontWeight: 600, fontSize: story ? 72 : 52, lineHeight: 1 };
  const statLbl: CSSProperties = { fontSize: story ? 22 : 17, color: C.muted };
  const capLbl: CSSProperties = { fontSize: 20, fontWeight: 500, letterSpacing: '0.08em', color: C.muted };
  const capVal: CSSProperties = { fontFamily: DISPLAY, fontWeight: 600, fontSize: 34 };
  const pctDone = Math.max(0, Math.min(100, data.progressPct ?? 0));
  const lostSign = data.lost > 0 ? '−' : data.lost < 0 ? '+' : '';

  const stats = [
    { v: int(data.avgSteps), l: 'ort. günlük adım' },
    { v: int(data.avgCalories), l: 'ort. günlük kcal' },
    { v: data.avgProtein === null ? '—' : `${int(data.avgProtein)} g`, l: 'ort. günlük protein' },
    data.stepGoal
      ? { v: `${data.stepHit}/${data.stepLogged}`, l: `gün ${int(data.stepGoal)}+ adım` }
      : { v: String(data.dayNumber), l: 'gün' },
  ];

  const photo = (src: string | null, empty: string) =>
    src ? (
      <img src={src} alt="" style={{ width: '100%', height: photoH, objectFit: 'cover', objectPosition: 'center 22%', borderRadius: 20, display: 'block' }} />
    ) : (
      <div style={{ height: photoH, boxSizing: 'border-box', border: `2px dashed ${C.line}`, borderRadius: 20, background: C.panel, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: DISPLAY, fontWeight: 600, fontSize: 40, letterSpacing: '0.08em', color: C.faint }}>
        {empty}
      </div>
    );

  return (
    <div
      style={{
        width: w, height: h, boxSizing: 'border-box', padding: story ? '190px 72px 250px' : '64px 72px', background: C.bg, color: C.fg, fontFamily: SANS,
        display: 'flex', flexDirection: 'column', gap: story ? 48 : 36, overflow: 'hidden',
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontFamily: DISPLAY, fontWeight: 700, fontSize: 34, letterSpacing: '0.18em', color: accent }}>DEĞİŞİM</span>
        <span style={{ fontFamily: DISPLAY, fontWeight: 500, fontSize: 30, letterSpacing: '0.06em', color: C.muted }}>
          GÜN {data.dayNumber} · {up(dayShort(data.startDate))} → {up(dayShort(data.lastDay))}
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {photo(beforeSrc, 'ÖNCE')}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={capLbl}>ÖNCE · {up(dayLong(data.before?.day ?? data.startDate))}</span>
            <span style={capVal}>{kg(data.startWeight)} kg</span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {photo(afterSrc, 'ŞİMDİ')}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={capLbl}>ŞİMDİ · {up(dayLong(data.after?.day ?? data.lastDay))}</span>
            <span style={{ ...capVal, color: accent }}>{kg(data.current)} kg</span>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24 }}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span style={{ fontFamily: DISPLAY, fontWeight: 700, fontSize: 188, lineHeight: 0.86, letterSpacing: '-0.01em', color: accent }}>
            {lostSign}{kg(Math.abs(data.lost))} kg
          </span>
          <span style={{ fontSize: 24, color: C.muted, marginTop: 14 }}>{data.dayNumber} günde {data.lost >= 0 ? 'verildi' : 'değişim'}</span>
        </div>
        {data.remaining !== null && (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, paddingBottom: 6 }}>
            <span style={{ fontSize: 18, fontWeight: 500, letterSpacing: '0.08em', color: C.muted }}>HEDEFE KALAN</span>
            <span style={{ fontFamily: DISPLAY, fontWeight: 600, fontSize: 64, lineHeight: 1 }}>{kg(data.remaining)} kg</span>
          </div>
        )}
      </div>

      {data.goalWeight !== null && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ height: 14, borderRadius: 999, background: '#2A2C27', overflow: 'hidden' }}>
            <div style={{ width: `${pctDone}%`, height: '100%', borderRadius: 999, background: accent }} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 18, color: C.muted }}>
            <span>{kg(data.startWeight)} kg</span>
            <span style={{ color: C.fg, fontWeight: 500 }}>%{int(pctDone)} tamamlandı</span>
            <span>
              Hedef {kg(data.goalWeight)} kg{data.goalDate ? ` · ${yearLong(data.goalDate)}` : ''}
            </span>
          </div>
        </div>
      )}

      <div
        style={{
          display: 'grid', gridTemplateColumns: story ? '1fr 1fr' : 'repeat(4, 1fr)', rowGap: 32, columnGap: story ? 24 : 16,
          borderTop: `1px solid ${C.line}`, paddingTop: 28,
        }}
      >
        {stats.map((s) => (
          <div key={s.l} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <span style={statNum}>{s.v}</span>
            <span style={statLbl}>{s.l}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

export default function Visual({ data }: { data: VisualData }) {
  const [format, setFormat] = useState<Format>('post');
  const [accent, setAccent] = useState(ACCENTS[0].hex);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const stageRef = useRef<HTMLDivElement>(null);
  const nodeRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState(0.4);
  const beforeSrc = useDataUrl(data.before?.url);
  const afterSrc = useDataUrl(data.after?.url);
  const { w, h } = SIZES[format];

  useLayoutEffect(() => {
    const el = stageRef.current;
    if (!el) return;
    const fit = () => setScale(Math.min(1, el.clientWidth / w));
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(el);
    return () => ro.disconnect();
  }, [w]);

  async function download() {
    if (!nodeRef.current) return;
    setBusy(true);
    setError(null);
    try {
      await document.fonts.ready;
      await Promise.all([...nodeRef.current.querySelectorAll('img')].map((i) => i.decode().catch(() => undefined)));
      const url = await toPng(nodeRef.current, { width: w, height: h, pixelRatio: 1, cacheBust: false, style: { transform: 'none' } });
      const a = document.createElement('a');
      const slug = data.name.toLocaleLowerCase('tr-TR').replace(/[^a-z0-9çğıöşü]+/gi, '-').replace(/^-|-$/g, '');
      a.download = `degisim-${slug}-${data.lastDay}-${format === 'post' ? 'gonderi' : 'story'}.png`;
      a.href = url;
      a.click();
    } catch {
      setError('PNG oluşturulamadı. Sayfayı yenileyip tekrar dene.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="stack" style={{ gap: 20 }}>
      <div className="row between">
        <div className="tabs" role="tablist" aria-label="Biçim">
          {(Object.keys(SIZES) as Format[]).map((f) => (
            <a
              key={f}
              href="#"
              role="tab"
              aria-selected={format === f}
              className={format === f ? 'on' : ''}
              onClick={(e) => {
                e.preventDefault();
                setFormat(f);
              }}
            >
              {SIZES[f].label}
            </a>
          ))}
        </div>
        <div className="row">
          <span className="muted" style={{ fontSize: 13 }}>Vurgu</span>
          {ACCENTS.map((a) => (
            <button
              key={a.hex}
              type="button"
              aria-label={`Vurgu rengi: ${a.name}`}
              aria-pressed={accent === a.hex}
              onClick={() => setAccent(a.hex)}
              style={{
                width: 32, height: 32, borderRadius: 999, background: a.hex, cursor: 'pointer',
                border: accent === a.hex ? '3px solid #F2F2EC' : '3px solid transparent', outline: '1px solid #2e302a',
              }}
            />
          ))}
          <button className="btn" onClick={download} disabled={busy}>
            {busy ? 'Hazırlanıyor…' : 'PNG indir'}
          </button>
        </div>
      </div>
      {error && <p className="msg error">{error}</p>}
      <div ref={stageRef} className="visual-stage" style={{ height: h * scale, maxWidth: format === 'story' ? 480 : 640 }}>
        <div className="visual-scale" style={{ width: w, height: h, transform: `scale(${scale})` }}>
          <div ref={nodeRef}>
            <Canvas data={data} format={format} accent={accent} beforeSrc={beforeSrc} afterSrc={afterSrc} />
          </div>
        </div>
      </div>
      {!data.after && <p className="faint" style={{ margin: 0, fontSize: 13 }}>“Şimdi” fotoğrafı için admin panelinden ikinci bir fotoğraf yüklenmeli.</p>}
    </div>
  );
}
