'use client'

/**
 * SloViolationChart — 30d 違反事件時序 BarChart
 * ==============================================
 * Recharts BarChart stacked，每 event_type 一色
 * X 軸：DD/MM 日期，Y 軸：count
 *
 * @created 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5
 */

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  ResponsiveContainer,
  CartesianGrid,
} from 'recharts'
import { useTranslations } from 'next-intl'
import { GlassCard } from '@/components/ui/glass-card'
import { AlertTriangle } from 'lucide-react'

// =============================================================================
// Types
// =============================================================================

export interface ViolationDataPoint {
  date: string        // ISO date string YYYY-MM-DD
  [eventType: string]: string | number
}

interface SloViolationChartProps {
  data: ViolationDataPoint[]
  eventTypes: string[]
  loading?: boolean
  error?: boolean
}

// =============================================================================
// Colour palette for event types (up to 6)
// =============================================================================

const EVENT_TYPE_COLORS = [
  '#d97757',  // accent coral
  '#4A90D9',  // blue
  '#22C55E',  // green
  '#F59E0B',  // amber
  '#8B5CF6',  // violet
  '#EC4899',  // pink
]

// =============================================================================
// Custom Tooltip
// =============================================================================

function CustomTooltip({ active, payload, label }: {
  active?: boolean
  payload?: Array<{ name: string; value: number; color: string }>
  label?: string
}) {
  if (!active || !payload?.length) return null
  return (
    <div style={{
      background: '#fff',
      border: '0.5px solid #e0ddd4',
      borderRadius: 8,
      padding: '8px 12px',
      boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
    }}>
      <div style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#87867f', marginBottom: 4 }}>
        {label}
      </div>
      {payload.map(entry => (
        <div key={entry.name} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#141413', fontFamily: "'DM Mono', monospace" }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: entry.color, flexShrink: 0 }} />
          <span style={{ color: '#87867f' }}>{entry.name}</span>
          <span style={{ fontWeight: 600, marginLeft: 'auto', paddingLeft: 8 }}>{entry.value}</span>
        </div>
      ))}
    </div>
  )
}

// =============================================================================
// Skeleton
// =============================================================================

function ChartSkeleton() {
  return (
    <div style={{ height: 200, display: 'flex', alignItems: 'flex-end', gap: 4, padding: '16px 0 8px' }}>
      {Array.from({ length: 15 }).map((_, i) => (
        <div
          key={i}
          style={{
            flex: 1,
            background: '#e0ddd4',
            borderRadius: '2px 2px 0 0',
            height: `${20 + Math.sin(i * 0.8) * 40 + 40}px`,
            animation: 'pulse 1.5s infinite',
            animationDelay: `${i * 0.05}s`,
          }}
        />
      ))}
    </div>
  )
}

// =============================================================================
// Component
// =============================================================================

export function SloViolationChart({ data, eventTypes, loading = false, error = false }: SloViolationChartProps) {
  const t = useTranslations('governance.slo.chart')

  const formattedData = data.map(d => ({
    ...d,
    label: new Date(d.date).toLocaleDateString('zh-TW', { month: '2-digit', day: '2-digit' }),
  }))

  return (
    <GlassCard variant="default" padding="lg">
      {/* Title */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <span style={{
          fontFamily: 'Syne, sans-serif',
          fontSize: 13,
          fontWeight: 700,
          color: '#141413',
          letterSpacing: '0.3px',
        }}>
          {t('title')}
        </span>
      </div>

      {/* States */}
      {loading && <ChartSkeleton />}

      {error && !loading && (
        <div style={{ height: 180, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <AlertTriangle size={20} style={{ color: '#F59E0B' }} />
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 12, color: '#87867f' }}>{t('error')}</span>
        </div>
      )}

      {!loading && !error && data.length === 0 && (
        <div style={{ height: 180, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <div style={{ width: 32, height: 32, borderRadius: '50%', background: '#22C55E22', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 12, height: 12, borderRadius: '50%', background: '#22C55E' }} />
          </div>
          <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 12, color: '#87867f' }}>{t('empty')}</span>
        </div>
      )}

      {!loading && !error && data.length > 0 && (
        <ResponsiveContainer width="100%" height={180}>
          <BarChart data={formattedData} margin={{ top: 4, right: 8, bottom: 0, left: -16 }} barSize={6}>
            <CartesianGrid vertical={false} stroke="#e0ddd4" strokeWidth={0.5} />
            <XAxis
              dataKey="label"
              tick={{ fontFamily: "'DM Mono', monospace", fontSize: 9, fill: '#87867f' }}
              axisLine={false}
              tickLine={false}
              interval="preserveStartEnd"
            />
            <YAxis
              tick={{ fontFamily: "'DM Mono', monospace", fontSize: 9, fill: '#87867f' }}
              axisLine={false}
              tickLine={false}
              allowDecimals={false}
            />
            <Tooltip content={<CustomTooltip />} />
            <Legend
              wrapperStyle={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#87867f', paddingTop: 8 }}
              iconSize={8}
              iconType="square"
            />
            {eventTypes.map((et, idx) => (
              <Bar
                key={et}
                dataKey={et}
                stackId="violations"
                fill={EVENT_TYPE_COLORS[idx % EVENT_TYPE_COLORS.length]}
                radius={idx === eventTypes.length - 1 ? [2, 2, 0, 0] : [0, 0, 0, 0]}
              />
            ))}
          </BarChart>
        </ResponsiveContainer>
      )}
    </GlassCard>
  )
}
