import { BookOpen, Compass, Heart, Scale, Briefcase } from 'lucide-react';
import { calculateBoneWeight, formatLiang } from '@/lib/bazi/boneWeight';
import { DIRECTION_NAMES, KUA_GROUP_NAME, KUA_TRIGRAM, calculateKua, directionKinds, type Gender } from '@/lib/bazi/kua';
import { readCareer, readEducation, readJodoh } from '@/lib/bazi/lifeAreas';
import { ELEMENT_INFO } from '@/lib/bazi/guide';
import { useLocale, useMessages } from '@/i18n/client';
import { ELEMENT_STYLE } from '@/components/insights/elements';
import { BoneWeightScale, DirectionBadge, KuaCompass } from '@/components/insights/DestinyVisuals';
import { cn } from '@/lib/cn';
import { BulletList, Card, CardTitle, Chapter, Prose, SampleNotice, type ReportModel } from './ReportChapters';

interface Props {
  profile: ReportModel;
  onAsk?: (question: string) => void;
  /** Opens the BaZi form so missing birth data can be entered. */
  onComplete: () => void;
}

function MissingBirthData({ profile, onComplete, what }: Props & { what: string }) {
  const t = useMessages().report.missing;
  return <SampleNotice text={t.text(what)} action={t.action} onAction={profile.canEdit ? onComplete : undefined} />;
}

function SampleBanner({ profile, onComplete }: Props) {
  const t = useMessages().report.missing;
  if (!profile.isSample.bazi) return null;
  return <SampleNotice text={t.sample} action={t.action} onAction={profile.canEdit ? onComplete : undefined} />;
}

/* ------------------------------------------------------------------ */
/* Skor Tulang                                                         */
/* ------------------------------------------------------------------ */

export function BoneWeightChapter(props: Props) {
  const { profile, onAsk } = props;
  const locale = useLocale();
  const m = useMessages().report;
  const t = m.bone;
  const input = profile.bazi.input;
  const bw = input ? calculateBoneWeight(input.birthDate, input.birthTime, locale) : null;

  return (
    <Chapter
      id="skor-tulang"
      title={m.view.chapters['skor-tulang']}
      lead={bw ? t.lead(bw.liang, bw.chinese, bw.reading.title) : t.leadEmpty}
      onAsk={onAsk && bw ? () => onAsk(t.ask(bw.liang)) : undefined}
    >
      <SampleBanner {...props} />
      <Card className="bg-canvas shadow-none">
        <CardTitle icon={Scale}>{t.whatTitle}</CardTitle>
        <Prose>{t.whatText}</Prose>
        <p className="mt-3 text-xs leading-relaxed text-muted">{t.unit}</p>
      </Card>

      {!bw ? (
        <MissingBirthData {...props} what={t.missing} />
      ) : (
        <>
          <Card>
            <div className="flex flex-col gap-6 sm:flex-row sm:items-center">
              <div className="shrink-0 text-center sm:w-44">
                <p className="eyebrow text-subtle">{t.yours}</p>
                <p className="mt-2 text-5xl font-semibold tracking-tight text-ink tabular-nums">{bw.liang}</p>
                <p className="mt-1 font-serif text-lg text-earth">{bw.chinese}</p>
                <p className="text-xs text-subtle">{t.tael}</p>
              </div>
              <div className="min-w-0 flex-1">
                <h3 className="text-xl font-semibold text-ink">{bw.reading.title}</h3>
                <Prose>{bw.reading.summary}</Prose>
                <BoneWeightScale totalQian={bw.totalQian} />
              </div>
            </div>
          </Card>

          <Card>
            <CardTitle>{t.breakdown}</CardTitle>
            <Prose>{t.lunar(bw.lunarDate)}</Prose>
            <table className="mt-4 w-full text-sm">
              <tbody className="divide-y divide-line">
                {bw.parts.map((p) => (
                  <tr key={p.label}>
                    <td className="py-2.5 text-muted">{p.label}</td>
                    <td className="py-2.5 text-ink-soft">{p.value}</td>
                    <td className="py-2.5 text-right font-medium text-ink tabular-nums">{formatLiang(p.qian).liang}</td>
                  </tr>
                ))}
                <tr>
                  <td className="pt-3 font-semibold text-ink" colSpan={2}>
                    {t.total}
                  </td>
                  <td className="pt-3 text-right font-semibold text-ink tabular-nums">{bw.liang}</td>
                </tr>
              </tbody>
            </table>
          </Card>

          <div className="grid gap-4 md:grid-cols-3">
            {[
              [t.youth, bw.reading.youth],
              [t.middle, bw.reading.middle],
              [t.later, bw.reading.later],
            ].map(([k, v]) => (
              <Card key={k}>
                <p className="eyebrow text-subtle">{k}</p>
                <p className="mt-3 text-sm leading-relaxed text-ink-soft">{v}</p>
              </Card>
            ))}
          </div>

          <Card className="bg-canvas shadow-none">
            <CardTitle>{t.advice}</CardTitle>
            <Prose>{bw.reading.advice}</Prose>
          </Card>
        </>
      )}
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */
/* Arah Mata Angin                                                     */
/* ------------------------------------------------------------------ */

export function DirectionChapter(props: Props) {
  const { profile, onAsk } = props;
  const locale = useLocale();
  const all = useMessages();
  const m = all.report;
  const t = m.direction;
  const names = DIRECTION_NAMES[locale];
  const kinds = directionKinds(locale);
  const input = profile.bazi.input;
  const kua = input ? calculateKua(input.birthDate, input.gender) : null;
  const trigram = kua ? KUA_TRIGRAM[kua.kua] : null;
  const group = kua ? KUA_GROUP_NAME[locale][kua.group] : '';
  const gender = input ? t.gender[input.gender] : '';

  return (
    <Chapter
      id="arah"
      title={m.view.chapters.arah}
      lead={kua ? t.lead(kua.kua, group, names[kua.directions[0].direction].name) : t.leadEmpty}
      onAsk={onAsk && kua ? () => onAsk(t.ask(kua.kua)) : undefined}
    >
      <SampleBanner {...props} />
      <Card className="bg-canvas shadow-none">
        <CardTitle icon={Compass}>{t.whatTitle}</CardTitle>
        <Prose>{t.whatText}</Prose>
      </Card>

      {!kua || !input ? (
        <MissingBirthData {...props} what={t.missing} />
      ) : (
        <>
          <Card>
            <div className="grid items-center gap-6 md:grid-cols-[300px_minmax(0,1fr)]">
              <KuaCompass kua={kua} className="mx-auto w-full max-w-[300px]" />
              <div>
                <p className="eyebrow text-subtle">{t.yours}</p>
                <h3 className="mt-2 text-2xl font-semibold text-ink">
                  Kua {kua.kua} <span className="font-serif text-earth">{trigram?.trigram}</span>{' '}
                  <span className="text-base font-normal text-subtle">
                    {trigram?.name} · {trigram && ELEMENT_INFO[locale][trigram.element].name}
                  </span>
                </h3>
                <Prose>
                  {t.computed(kua.year, gender)} {kua.kua === 5 && t.kua5(kua.effective, gender)}{' '}
                  <span className="font-semibold text-ink">{t.group(group)}</span>
                  {kua.group === 'east' ? t.groupEast : t.groupWest}
                </Prose>
                <p className="mt-3 text-xs text-muted">{t.legend}</p>
              </div>
            </div>
          </Card>

          <div className="grid gap-4 md:grid-cols-2">
            {kua.directions.map(({ kind, direction }) => {
              const info = kinds[kind];
              return (
                <Card key={kind} className={cn(!info.good && 'bg-canvas shadow-none')}>
                  <p className="flex flex-wrap items-center gap-2">
                    <span className="text-lg font-semibold text-ink">{names[direction].name}</span>
                    <DirectionBadge good={info.good}>{info.good ? t.good(info.rank) : t.avoid(info.rank - 4)}</DirectionBadge>
                  </p>
                  <p className="mt-1 text-sm text-muted">
                    {info.name} <span className="font-serif">{info.chinese}</span> · {info.label}
                  </p>
                  <p className="mt-3 text-sm leading-relaxed text-ink-soft">{info.meaning}</p>
                  <p className="mt-2 text-[13px] leading-relaxed text-muted">{info.use}</p>
                </Card>
              );
            })}
          </div>

          <Card className="bg-canvas shadow-none">
            <CardTitle>{t.howTitle}</CardTitle>
            <BulletList items={t.how} />
          </Card>
        </>
      )}
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */
/* Karier (BaZi sections inside the career chapter)                    */
/* ------------------------------------------------------------------ */

export function CareerBaziSections({ profile }: { profile: ReportModel }) {
  const locale = useLocale();
  const t = useMessages().report.career;
  const info = ELEMENT_INFO[locale];
  const c = readCareer(profile.bazi, locale);
  const input = profile.bazi.input;
  const kua = input ? calculateKua(input.birthDate, input.gender) : null;
  const sq = kua?.directions.find((d) => d.kind === 'sheng_qi');

  return (
    <>
      <Card>
        <p className="eyebrow text-subtle">{t.archetypeEyebrow}</p>
        <h3 className="mt-2 text-xl font-semibold text-ink">{c.archetype.title}</h3>
        <Prose>{c.archetype.text}</Prose>
        <p className="mt-3 text-sm text-ink-soft">
          <span className="font-medium text-ink">{t.roles}</span>
          {c.archetype.roles}
        </p>
        <p className="mt-3 text-xs text-muted">{t.archetypeNote(c.second.title)}</p>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardTitle icon={Briefcase}>{t.workStyle}</CardTitle>
          <Prose>{c.workStyle}</Prose>
        </Card>
        <Card>
          <CardTitle>
            {t.wealthStar} <span className={ELEMENT_STYLE[c.wealth.element].text}>{info[c.wealth.element].name}</span>
          </CardTitle>
          <p className="mt-1 text-xs text-muted">{t.strength(c.wealth.level)}</p>
          <Prose>{c.wealth.text}</Prose>
        </Card>
      </div>

      <Card>
        <CardTitle>{t.industries}</CardTitle>
        <Prose>{t.industriesText}</Prose>
        <ul className="mt-4 space-y-3">
          {c.industries.map(({ element, careers }) => (
            <li key={element} className="flex gap-3 text-sm leading-relaxed">
              <span className={cn('w-14 shrink-0 font-semibold', ELEMENT_STYLE[element].text)}>{info[element].name}</span>
              <span className="text-ink-soft">{careers}</span>
            </li>
          ))}
        </ul>
      </Card>

      {sq && (
        <Card className="bg-canvas shadow-none">
          <CardTitle icon={Compass}>{t.directionTitle}</CardTitle>
          <Prose>
            {t.directionText[0]}
            <span className="font-semibold text-ink">{DIRECTION_NAMES[locale][sq.direction].name}</span>
            {t.directionText[1]}
          </Prose>
        </Card>
      )}
    </>
  );
}

/* ------------------------------------------------------------------ */
/* Pendidikan                                                          */
/* ------------------------------------------------------------------ */

export function EducationChapter(props: Props) {
  const { profile, onAsk } = props;
  const locale = useLocale();
  const t = useMessages().report.education;
  const info = ELEMENT_INFO[locale];
  const names = DIRECTION_NAMES[locale];
  const e = readEducation(profile.bazi, locale);
  const input = profile.bazi.input;
  const kua = input ? calculateKua(input.birthDate, input.gender) : null;
  const fw = kua?.directions.find((d) => d.kind === 'fu_wei');
  const wc = t.wenChangText(e.wenChang.animal, e.wenChang.branch);

  return (
    <Chapter id="pendidikan" title={t.title} lead={t.lead} onAsk={onAsk && (() => onAsk(t.ask))}>
      <SampleBanner {...props} />
      <Card>
        <CardTitle icon={BookOpen}>{t.style}</CardTitle>
        <Prose>{e.style}</Prose>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        {[
          { title: t.resource, r: e.resource },
          { title: t.output, r: e.output },
        ].map(({ title, r }) => {
          const [pre, el, post] = t.elementLevel(info[r.element].name, r.level);
          return (
            <Card key={title}>
              <CardTitle>{title}</CardTitle>
              <p className="mt-1 text-xs text-muted">
                {pre}
                <span className={cn('font-semibold', ELEMENT_STYLE[r.element].text)}>{el}</span>
                {post}
              </p>
              <Prose>{r.text}</Prose>
            </Card>
          );
        })}
      </div>

      <Card>
        <CardTitle>{t.fields}</CardTitle>
        <ul className="mt-4 space-y-3">
          {e.fields.map(({ element, fields }) => (
            <li key={element} className="flex gap-3 text-sm leading-relaxed">
              <span className={cn('w-14 shrink-0 font-semibold', ELEMENT_STYLE[element].text)}>{info[element].name}</span>
              <span className="text-ink-soft">{fields}</span>
            </li>
          ))}
        </ul>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardTitle>
            {t.wenChang} <span className="font-serif font-normal text-subtle">文昌</span>
          </CardTitle>
          <Prose>
            {wc[0]}
            <span className="font-semibold text-ink">{wc[1]}</span>
            {wc[2]}
            {e.wenChang.present ? t.wenChangPresent : t.wenChangAbsent}
          </Prose>
        </Card>
        {fw && kua && (
          <Card>
            <CardTitle icon={Compass}>{t.deskTitle}</CardTitle>
            {(() => {
              const [pre, dir, post] = t.deskText(names[fw.direction].name, names[kua.directions[0].direction].name);
              return (
                <Prose>
                  {pre}
                  <span className="font-semibold text-ink">{dir}</span>
                  {post}
                </Prose>
              );
            })()}
          </Card>
        )}
      </div>
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */
/* Jodoh (BaZi sections inside the relationship chapter)              */
/* ------------------------------------------------------------------ */

export function JodohSections(props: Props) {
  const { profile } = props;
  const locale = useLocale();
  const t = useMessages().report.jodoh;
  const info = ELEMENT_INFO[locale];
  const gender: Gender | undefined = profile.bazi.input?.gender;
  if (!gender) return <MissingBirthData {...props} what={t.missing} />;

  const j = readJodoh(profile.bazi, gender, locale);
  const kua = calculateKua(profile.bazi.input!.birthDate, gender);
  const yn = kua.directions.find((d) => d.kind === 'yan_nian')!;
  const peach = t.peachText(j.peachBlossom.animal, j.peachBlossom.branch);
  const dirText = t.directionText(DIRECTION_NAMES[locale][yn.direction].name);

  return (
    <>
      <Card>
        <CardTitle icon={Heart}>
          {t.palace(j.spousePalace.animal)}{' '}
          <span className={cn('font-serif', ELEMENT_STYLE[j.spousePalace.element].text)}>{j.spousePalace.branch}</span>
        </CardTitle>
        <Prose>
          {t.palaceText}
          {j.spousePalace.text}
        </Prose>
      </Card>

      <Card>
        <CardTitle>
          {j.spouseStar.label}:{' '}
          <span className={ELEMENT_STYLE[j.spouseStar.element].text}>{info[j.spouseStar.element].name}</span>
        </CardTitle>
        <p className="mt-1 text-xs text-muted">{t.level(j.spouseStar.level)}</p>
        <Prose>{j.spouseStar.text}</Prose>
        <p className="mt-3 text-sm text-ink-soft">
          <span className="font-medium text-ink">{t.complement}</span>
          {j.idealPartner}
        </p>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardTitle>{t.compatible}</CardTitle>
          <ul className="mt-4 space-y-3">
            {j.compatible.map((s) => (
              <li key={s.branch} className="text-sm">
                <p className="font-semibold text-ink">
                  <span className="font-serif text-wood">{s.branch}</span> {s.animal}
                </p>
                <p className="text-[13px] text-muted">{s.reason}</p>
              </li>
            ))}
          </ul>
        </Card>
        <Card>
          <CardTitle>{t.avoid}</CardTitle>
          <ul className="mt-4 space-y-3">
            {j.avoid.map((s) => (
              <li key={s.branch} className="text-sm">
                <p className="font-semibold text-ink">
                  <span className="font-serif text-fire">{s.branch}</span> {s.animal}
                </p>
                <p className="text-[13px] text-muted">{s.reason}</p>
              </li>
            ))}
          </ul>
          <p className="mt-4 text-xs text-muted">{t.avoidNote}</p>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardTitle>
            {t.peach} <span className="font-serif font-normal text-subtle">桃花</span>
          </CardTitle>
          <Prose>
            {peach[0]}
            <span className="font-semibold text-ink">{peach[1]}</span>
            {peach[2]}
            {j.peachBlossom.present ? t.peachPresent : t.peachAbsent}
          </Prose>
        </Card>
        <Card>
          <CardTitle icon={Compass}>{t.directionTitle}</CardTitle>
          <Prose>
            {dirText[0]}
            <span className="font-semibold text-ink">{dirText[1]}</span>
            {dirText[2]}
          </Prose>
        </Card>
      </div>
    </>
  );
}
