'use client'

import { useMemo, useState } from 'react'
import Link from 'next/link'

import { useI18n } from '@/components/providers/i18n-provider'
import { Badge, KeyValue, Meter } from '@/components/ui/display'
import { Segmented } from '@/components/ui/controls'
import { DNA_FEATURES, dnaSimilarity, type DnaVector } from '@/lib/engine/dna'
import { riskToState } from '@/lib/domain/enums'
import { cn } from '@/lib/cn'
import { styleForRisk } from '@/lib/ui/state-styles'

export interface DnaPatternView {
  code: string
  patternCode: string
  name: string
  nameAr: string
  description: string
  descriptionAr: string
  eventType: string
  severity: string
  occurredAt: number
  regionName: string | null
  regionNameAr: string | null
  assetTypeKey: string
  durationMin: number
  customersAffect: number
  energyLostMwh: number
  outcome: string
  outcomeAr: string
  vector: Record<string, number>
}

export interface DnaCurrentMatch {
  assetCode: string
  regionCode: string
  riskScore: number
  similarity: number
  dnaCode: string | null
  vector: Record<string, number>
}

/**
 * The Failure DNA workbench.
 *
 * Pick a historical signature and a live asset, and the two are laid over each other
 * dimension by dimension. The similarity number recomputes in the browser from the same
 * function the server uses, so what the operator sees here is not a cached score but the
 * actual comparison being made.
 */
export function DnaExplorer({
  patterns,
  matches,
  focus,
}: {
  patterns: DnaPatternView[]
  matches: DnaCurrentMatch[]
  focus?: string
}) {
  const { t, locale, n, date, duration } = useI18n()

  const [selectedPattern, setSelectedPattern] = useState(
    () => patterns.find((pattern) => pattern.code === focus)?.code ?? patterns[0]?.code ?? '',
  )
  const [selectedAsset, setSelectedAsset] = useState(matches[0]?.assetCode ?? '')

  const pattern = patterns.find((entry) => entry.code === selectedPattern) ?? patterns[0]
  const match = matches.find((entry) => entry.assetCode === selectedAsset) ?? matches[0]

  // Recomputed live rather than read from a field, so the comparison on screen is always
  // between the two signatures actually shown.
  const similarity = useMemo(() => {
    if (!pattern || !match) return 0
    return dnaSimilarity(match.vector as unknown as DnaVector, pattern.vector as unknown as DnaVector)
  }, [pattern, match])

  if (!pattern) {
    return <p className="py-8 text-center text-sm text-text-muted">{t('dna.empty')}</p>
  }

  return (
    <div className="grid gap-6 lg:grid-cols-[300px_1fr]">
      {/* Library */}
      <div className="max-h-[640px] space-y-1.5 overflow-y-auto pe-1">
        <p className="sticky top-0 z-10 bg-surface pb-2 text-[10px] font-semibold uppercase tracking-wide text-text-faint">
          {t('dna.library')}
        </p>
        {patterns.map((entry) => {
          const active = entry.code === pattern.code
          return (
            <button
              key={entry.code}
              type="button"
              onClick={() => setSelectedPattern(entry.code)}
              className={cn(
                'w-full rounded-lg border p-3 text-start transition-colors',
                active
                  ? 'border-brand/50 bg-brand/8'
                  : 'border-border bg-surface-2/40 hover:border-border-strong',
              )}
            >
              <div className="flex items-center justify-between gap-2">
                <span className={cn('font-mono text-[11px]', active ? 'text-brand' : 'text-text-muted')}>
                  {entry.code}
                </span>
                <span className="text-[10px] text-text-faint">{date(entry.occurredAt)}</span>
              </div>
              <p className="mt-1.5 line-clamp-2 text-xs leading-snug text-text">
                {locale === 'ar' ? entry.nameAr : entry.name}
              </p>
              <p className="mt-1 text-[10px] text-text-faint">
                {t(`eventType.${entry.eventType}`)} · {t(`severity.${entry.severity}`)}
              </p>
            </button>
          )
        })}
      </div>

      {/* Detail */}
      <div className="space-y-5">
        <div className="rounded-lg border border-border bg-surface-2/40 p-5">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <Badge tone="brand">{pattern.code}</Badge>
                <Badge tone="muted">{t(`eventType.${pattern.eventType}`)}</Badge>
                <Badge tone="muted">{t(`assetType.${pattern.assetTypeKey}`)}</Badge>
              </div>
              <h3 className="mt-2.5 text-base font-semibold text-text">
                {locale === 'ar' ? pattern.nameAr : pattern.name}
              </h3>
              <p className="mt-2 max-w-2xl text-sm leading-relaxed text-text-muted">
                {locale === 'ar' ? pattern.descriptionAr : pattern.description}
              </p>
            </div>
          </div>

          <dl className="mt-4 grid gap-x-8 gap-y-1 border-t border-border pt-4 sm:grid-cols-2 lg:grid-cols-3">
            <KeyValue label={t('dna.occurred')} value={date(pattern.occurredAt)} />
            {pattern.regionName ? (
              <KeyValue
                label={t('common.region')}
                value={locale === 'ar' ? pattern.regionNameAr! : pattern.regionName}
              />
            ) : null}
            {pattern.durationMin > 0 ? (
              <KeyValue label={t('dna.duration')} value={duration(pattern.durationMin)} />
            ) : null}
            {pattern.customersAffect > 0 ? (
              <KeyValue
                label={t('dna.customersAffected')}
                value={n(pattern.customersAffect)}
                mono
              />
            ) : null}
            {pattern.energyLostMwh > 0 ? (
              <KeyValue
                label={t('dna.energyLost')}
                value={`${n(pattern.energyLostMwh, { maximumFractionDigits: 1 })} ${t('common.units.mwh')}`}
                mono
              />
            ) : null}
          </dl>

          <p className="mt-3 rounded-lg border border-border bg-surface/60 px-3 py-2.5 text-xs leading-relaxed text-text-muted">
            <span className="font-medium text-text">{t('dna.outcome')}: </span>
            {locale === 'ar' ? pattern.outcomeAr : pattern.outcome}
          </p>
        </div>

        {/* Comparison */}
        {match ? (
          <div className="rounded-lg border border-border bg-surface-2/40 p-5">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-wide text-text-faint">
                  {t('dna.compare')}
                </p>
                <Segmented
                  ariaLabel={t('dna.current')}
                  className="mt-2"
                  size="sm"
                  value={match.assetCode}
                  onChange={setSelectedAsset}
                  options={matches.slice(0, 6).map((entry) => ({
                    value: entry.assetCode,
                    label: entry.assetCode,
                    title: `${t('common.risk')} ${Math.round(entry.riskScore)}%`,
                  }))}
                />
              </div>

              <div className="text-end">
                <p className="text-[10px] uppercase tracking-wide text-text-faint">
                  {t('dna.similarity')}
                </p>
                <p className={cn('tnum text-4xl font-semibold', styleForRisk(similarity).text)}>
                  {n(similarity, { maximumFractionDigits: 0 })}%
                </p>
                <Link
                  href={`/assets/${encodeURIComponent(match.assetCode)}`}
                  className="mt-1 inline-block text-[11px] text-brand hover:underline"
                >
                  {match.assetCode} →
                </Link>
              </div>
            </div>

            <Meter
              value={similarity}
              state={riskToState(similarity)}
              className="mt-4"
            />

            <div className="mt-5 space-y-2 border-t border-border pt-4">
              <div className="flex items-center gap-3 text-[10px] uppercase tracking-wide text-text-faint">
                <span className="w-36 shrink-0">{t('dna.dimensions')}</span>
                <span className="flex-1">{t('dna.current')} / {t('dna.historical')}</span>
                <span className="w-12 text-end">{t('dna.agreement')}</span>
              </div>

              {DNA_FEATURES.map((feature) => {
                const current = match.vector[feature] ?? 0
                const historical = pattern.vector[feature] ?? 0
                const agreement = Math.max(0, 1 - Math.abs(current - historical)) * 100
                return (
                  <div key={feature} className="flex items-center gap-3">
                    <span className="w-36 shrink-0 truncate text-[11px] text-text-muted">
                      {t(`dnaFeature.${feature}`)}
                    </span>
                    <div className="relative h-4 flex-1 overflow-hidden rounded bg-surface-3">
                      <div
                        className="absolute inset-y-0 rounded bg-info/45"
                        style={{ insetInlineStart: 0, width: `${historical * 100}%` }}
                      />
                      <div
                        className="absolute inset-y-1 rounded bg-brand"
                        style={{ insetInlineStart: 0, width: `${current * 100}%` }}
                      />
                    </div>
                    <span
                      className={cn(
                        'tnum w-12 shrink-0 text-end text-[11px] font-medium',
                        agreement >= 85 ? 'text-normal' : agreement >= 60 ? 'text-watch' : 'text-text-faint',
                      )}
                    >
                      {n(agreement, { maximumFractionDigits: 0 })}%
                    </span>
                  </div>
                )
              })}
            </div>

            <div className="mt-4 flex flex-wrap items-center gap-4 border-t border-border pt-3 text-[11px] text-text-muted">
              <span className="flex items-center gap-1.5">
                <span className="size-2 rounded-sm bg-brand" /> {t('dna.current')}
              </span>
              <span className="flex items-center gap-1.5">
                <span className="size-2 rounded-sm bg-info/45" /> {t('dna.historical')}
              </span>
            </div>
          </div>
        ) : null}

        {/* Live matches */}
        <div>
          <p className="mb-2 text-[10px] font-semibold uppercase tracking-wide text-text-faint">
            {t('dna.matches')}
          </p>
          <ul className="space-y-1.5">
            {matches.map((entry) => (
              <li
                key={entry.assetCode}
                className="flex flex-wrap items-center gap-3 rounded-lg border border-border bg-surface-2/40 px-3 py-2.5"
              >
                <Link
                  href={`/assets/${encodeURIComponent(entry.assetCode)}`}
                  className="font-mono text-xs text-brand hover:underline"
                >
                  {entry.assetCode}
                </Link>
                <span className="text-[11px] text-text-faint">{entry.regionCode}</span>
                {entry.dnaCode ? (
                  <button
                    type="button"
                    onClick={() => {
                      setSelectedPattern(entry.dnaCode!)
                      setSelectedAsset(entry.assetCode)
                    }}
                    className="font-mono text-[11px] text-text-muted transition-colors hover:text-brand"
                  >
                    {entry.dnaCode}
                  </button>
                ) : null}
                <span className="ms-auto flex items-center gap-3">
                  <span className={cn('tnum text-xs', styleForRisk(entry.riskScore).text)}>
                    {t('common.risk')} {n(entry.riskScore, { maximumFractionDigits: 0 })}%
                  </span>
                  <span className={cn('tnum text-sm font-medium', styleForRisk(entry.similarity).text)}>
                    {n(entry.similarity, { maximumFractionDigits: 0 })}%
                  </span>
                </span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  )
}
