'use client'

import { useParams } from 'next/navigation'
import { useT } from '@/contexts/LangContext'
import Box from '@mui/material/Box'
import Grid from '@mui/material/Grid'
import Typography from '@mui/material/Typography'

import StatsBar from './StatsBar'
import NextHearingCard from './NextHearingCard'
import UrgentAlertsCard from './UrgentAlertsCard'
import CalendarCard from './CalendarCard'
import AiPromptBar from './AiPromptBar'
import ActiveMattersCard from './ActiveMattersCard'
import AgentActivityCard from './AgentActivityCard'
import BillingSnapshotCard from './BillingSnapshotCard'
import EmailsCard from './EmailsCard'
import UpcomingHearingsTable from './UpcomingHearingsTable'

import type { DashboardStats, Hearing, Matter, Alert, AgentActivity, RetainerAlert, Appointment } from './types'

const STATS: DashboardStats = { activeMatters: 24, hearingsThisWeek: 6, unbilledHours: 18.5, monthlyRevenue: 842000, currency: 'THB' }
const today = new Date().toISOString().split('T')[0]
const d = (n: number) => new Date(Date.now() + n * 86400000).toISOString().split('T')[0]

const HEARINGS: Hearing[] = [
  { id: 'h1', matterId: 'm1', matter: 'Smith v. Nexus — TM.7 Extension', client: 'James Smith', court: 'Civil Court Division 3', room: '4B', judge: 'Somchai Pattanarat', date: today, time: '09:30', status: 'confirmed' },
  { id: 'h2', matterId: 'm2', matter: 'Jones Immigration Appeal', client: 'Sarah Jones', court: 'Immigration Tribunal', date: d(2), time: '14:00', status: 'pending' },
  { id: 'h3', matterId: 'm3', matter: 'Rivera Visa Overstay', client: 'Carlos Rivera', court: 'Civil Court Division 1', room: '2A', judge: 'Wirut Arayachai', date: d(5), time: '10:00', status: 'confirmed' },
]

const MATTERS: Matter[] = [
  { id: 'm1', reference: 'TM.7 — Smith', client: 'James Smith', practiceArea: 'immigration', nextAction: 'Hearing', nextActionDate: today, nextActionType: 'hearing', status: 'active' },
  { id: 'm2', reference: 'BOI — Nexus Corp', client: 'Nexus Corp Ltd', practiceArea: 'corporate', nextAction: 'Filing', nextActionDate: d(5), nextActionType: 'filing', status: 'active' },
  { id: 'm3', reference: 'Visa — Tanaka K.', client: 'Kenji Tanaka', practiceArea: 'immigration', nextAction: 'Review', nextActionDate: d(8), nextActionType: 'review', status: 'active' },
  { id: 'm4', reference: 'Land — Siriwan', client: 'Siriwan Jaidee', practiceArea: 'property', nextAction: 'Deadline', nextActionDate: d(1), nextActionType: 'deadline', status: 'active' },
  { id: 'm5', reference: 'Chang Corp — Dispute', client: 'Chang Corp', practiceArea: 'civil_litigation', nextAction: 'Hearing', nextActionDate: d(12), nextActionType: 'hearing', status: 'active' },
  { id: 'm6', reference: 'Kim — Employment', client: 'Ji-woo Kim', practiceArea: 'employment', nextAction: 'Filing', nextActionDate: d(3), nextActionType: 'filing', status: 'active' },
]

// Appointments are client meetings, consultations, calls — distinct from court hearings
const t = (h: number, m: number) => `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`
const APPOINTMENTS: Appointment[] = [
  { id: 'ap1', matterId: 'm2', client: 'Nexus Corp Ltd',  title: 'BOI strategy review',       type: 'meeting',      date: today,  time: t(new Date().getHours(), new Date().getMinutes() + 45), location: 'Office — Conf Rm A' },
  { id: 'ap2', matterId: 'm6', client: 'Ji-woo Kim',      title: 'Employment dispute briefing', type: 'consultation', date: d(1),   time: '11:00', location: 'Office — Conf Rm B' },
  { id: 'ap3', matterId: 'm4', client: 'Siriwan Jaidee',  title: 'Land title signing',          type: 'signing',      date: d(3),   time: '14:30', location: 'Notary Office, Silom' },
  { id: 'ap4', matterId: 'm3', client: 'Kenji Tanaka',    title: 'Visa extension call',         type: 'call',         date: d(6),   time: '10:00' },
]

const ALERTS: Alert[] = [
  { id: 'a1', severity: 'urgent', type: 'deadline', matter: 'Visa — Jones', client: 'Sarah Jones', message: 'Visa expiry deadline — must file extension', daysUntil: 2 },
  { id: 'a2', severity: 'warning', type: 'retainer_low', matter: 'BOI — Nexus', client: 'Chang Corp', message: 'Retainer balance \u0e3f12,400 — below threshold' },
  { id: 'a3', severity: 'warning', type: 'response_required', matter: 'Kim — Employment', client: 'Ji-woo Kim', message: 'Response to opposing counsel required', daysUntil: 3 },
  { id: 'a4', severity: 'info', type: 'document_received', matter: 'Land — Siriwan', client: 'Siriwan Jaidee', message: 'Chanote deed received — needs classification' },
]

const AGENT_ACTIVITY: AgentActivity[] = [
  { id: 'ac1', activityType: 'document',  action: 'Reviewed incoming document',          matter: 'Visa — Jones',     timestamp: '2m ago', color: 'primary'   },
  { id: 'ac2', activityType: 'billing',   action: 'Quote sent: \u0e3f45,000',             matter: 'BOI — Nexus Corp', timestamp: '1h ago', color: 'success'   },
  { id: 'ac3', activityType: 'comms',     action: 'Hearing reminder sent via LINE',       matter: 'Smith v. Nexus',   timestamp: '3h ago', color: 'info'      },
  { id: 'ac4', activityType: 'research',  action: 'Checked current regulations',          matter: 'BOI — Nexus Corp', timestamp: '4h ago', color: 'warning'   },
  { id: 'ac5', activityType: 'check',     action: 'Conflict check: Rivera (new intake)',                              timestamp: '5h ago', color: 'secondary' },
]

const BILLING = {
  monthlyRevenue: 842000, monthlyTarget: 1200000, outstanding: 234000, overdue: 48000, currency: 'THB',
  retainerAlerts: [
    { client: 'Chang Corp', balance: 12400, currency: 'THB', threshold: 25000 },
    { client: 'Kenji Tanaka', balance: 8200, currency: 'THB', threshold: 20000 },
  ] as RetainerAlert[],
}

export default function AttorneyDashboard() {
  const params = useParams()
  const lang = (params?.lang as string) ?? 'en'
  const t = useT()
  const locale = lang === 'th' ? 'th-TH' : 'en-GB'
  const dateLabel = new Date().toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })
  const nextHearing = HEARINGS.find(h => h.date === today) ?? HEARINGS[0]

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      {/* Header */}
      <Box>
        <Typography variant='h4' sx={{ fontWeight: 600 }}>{t.dashboard.greeting}</Typography>
        <Typography variant='body2' color='text.secondary'>{dateLabel}</Typography>
      </Box>

      {/* Row 1 — AI Prompt Bar (full width) */}
      <AiPromptBar />

      {/* Row 2 — Stats */}
      <StatsBar stats={STATS} />

      {/* Row 3 — Alerts + Next Hearing + Inbox (left) | Calendar (right) */}
      <Box sx={{ display: 'flex', gap: 2, alignItems: 'stretch' }}>
        <Box sx={{ flex: '0 0 calc(66.67% - 8px)', display: 'flex', flexDirection: 'column', gap: 2 }}>
          <UrgentAlertsCard alerts={ALERTS} />
          <NextHearingCard hearing={nextHearing} />
          <EmailsCard />
        </Box>
        <Box sx={{ flex: '0 0 calc(33.33% - 8px)' }}>
          <CalendarCard hearings={HEARINGS} matters={MATTERS} appointments={APPOINTMENTS} fullViewHref={`/${lang}/calendar`} />
        </Box>
      </Box>

      {/* Row 5 — Matters + Agent Activity + Billing */}
      <Grid container spacing={2} alignItems='stretch'>
        <Grid size={{ xs: 12, md: 4 }}><ActiveMattersCard matters={MATTERS} /></Grid>
        <Grid size={{ xs: 12, md: 4 }}><AgentActivityCard activities={AGENT_ACTIVITY} viewAllHref={`/${lang}/agent-activity`} /></Grid>
        <Grid size={{ xs: 12, md: 4 }}><BillingSnapshotCard data={BILLING} /></Grid>
      </Grid>

      {/* Row 6 — Hearings Table */}
      <UpcomingHearingsTable hearings={HEARINGS} />
    </Box>
  )
}
