/**
 * Meetings Management Page
 *
 * Calendar grid + expandable meeting cards + sortable data table with CSV export.
 */
import { useState, useMemo, useCallback } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
    format, startOfMonth, endOfMonth, startOfWeek, endOfWeek,
    eachDayOfInterval, isSameMonth, isSameDay, isToday, addMonths, subMonths,
} from 'date-fns'
import type { Locale } from 'date-fns'
import { he, enUS } from 'date-fns/locale'
import {
    Calendar as CalendarIcon, Video, Clock, User, Phone, Mail,
    ChevronLeft, ChevronRight, ChevronDown, ChevronUp, X,
    ExternalLink, Download, Search, Filter, Globe, MessageSquare, FileText,
} from 'lucide-react'
import { Link } from 'react-router-dom'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { apiClient } from '@/api/client'
import { t, sprintf, isRtl } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'

// ── Types ────────────────────────────────────────────────────────────

interface Meeting {
    id: number
    conversation_id: string | null
    conversation_db_id: number | null
    chatbot_id: number | null
    widget_id: number | null
    customer_name: string
    customer_email: string
    customer_phone: string
    title: string
    description: string
    meeting_date: string
    start_time: string
    end_time: string
    timezone: string
    google_event_id: string | null
    google_meet_link: string | null
    google_calendar_link: string | null
    attendee_contacts: string | null
    custom_fields: string | null
    ai_summary: string | null
    status: 'scheduled' | 'confirmed' | 'cancelled' | 'completed' | 'no_show'
    reminder_sent: number
    confirmation_sent: number
    created_at: string
    updated_at?: string
}

interface MeetingStats {
    total: number
    scheduled: number
    confirmed: number
    completed: number
    cancelled: number
    no_show: number
}

type SortField = 'meeting_date' | 'start_time' | 'customer_name' | 'customer_email' | 'customer_phone' | 'status'
type SortDir = 'asc' | 'desc'

// ── Constants ────────────────────────────────────────────────────────

function getStatusConfig(): Record<string, { label: string; color: string; bg: string; dot: string }> {
    return {
        scheduled: { label: t('Scheduled'), color: 'text-blue-800', bg: 'bg-blue-100', dot: 'bg-blue-500' },
        confirmed: { label: t('Confirmed'), color: 'text-green-800', bg: 'bg-green-100', dot: 'bg-green-500' },
        cancelled: { label: t('Cancelled'), color: 'text-red-800', bg: 'bg-red-100', dot: 'bg-red-500' },
        completed: { label: t('Completed'), color: 'text-gray-700', bg: 'bg-gray-200', dot: 'bg-gray-500' },
        no_show:   { label: t('No Show'), color: 'text-orange-800', bg: 'bg-orange-100', dot: 'bg-orange-500' },
    }
}

function getStatusOptions() {
    return [
        { value: '', label: t('All Statuses') },
        { value: 'scheduled', label: t('Scheduled') },
        { value: 'confirmed', label: t('Confirmed') },
        { value: 'completed', label: t('Completed') },
        { value: 'cancelled', label: t('Cancelled') },
        { value: 'no_show', label: t('No Show') },
    ]
}

const DAY_LABELS: Record<string, string[]> = {
    he: ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳', 'ש׳'],
    en: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
}

const PAGE_SIZE = 20

// ── Helpers ──────────────────────────────────────────────────────────

function safeHostname(url: string): string {
    try { return new URL(url).hostname }
    catch { return url || '-' }
}

function parseCustomFields(raw: string | null): Record<string, string> {
    if (!raw) return {}
    try { return JSON.parse(raw) } catch { return {} }
}

function formatTime(t: string) {
    return t?.slice(0, 5) ?? ''
}

function formatDateLocalized(d: string, locale: Locale) {
    try {
        return format(new Date(d + 'T00:00:00'), 'EEEE, d MMMM yyyy', { locale })
    } catch {
        return d
    }
}

function meetingMatchesSearch(m: Meeting, q: string): boolean {
    const lower = q.toLowerCase()
    return (
        m.customer_name?.toLowerCase().includes(lower) ||
        m.customer_email?.toLowerCase().includes(lower) ||
        m.customer_phone?.includes(lower) ||
        m.title?.toLowerCase().includes(lower) ||
        false
    )
}

// ── Main Component ───────────────────────────────────────────────────

export function Meetings() {
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()

    // Calendar locale + day headers based on admin language
    const dateLocale = currentLanguage === 'en' ? enUS : he
    const dayHeaders = DAY_LABELS[currentLanguage] || DAY_LABELS.en

    // Calendar state
    const [currentMonth, setCurrentMonth] = useState(new Date())
    const [selectedDay, setSelectedDay] = useState<Date | null>(null)

    // Table state
    const [statusFilter, setStatusFilter] = useState('')
    const [searchQuery, setSearchQuery] = useState('')
    const [sortField, setSortField] = useState<SortField>('meeting_date')
    const [sortDir, setSortDir] = useState<SortDir>('desc')
    const [page, setPage] = useState(0)

    // Expanded meeting card
    const [expandedMeetingId, setExpandedMeetingId] = useState<number | null>(null)

    // Date range for data fetch (current month)
    const monthStart = startOfMonth(currentMonth)
    const monthEnd = endOfMonth(currentMonth)
    const startDate = format(monthStart, 'yyyy-MM-dd')
    const endDate = format(monthEnd, 'yyyy-MM-dd')

    // ── Queries ──────────────────────────────────────────────────────

    const { data: meetingsData, isLoading, isError } = useQuery({
        queryKey: ['meetings', startDate, endDate, currentLanguage],
        queryFn: () =>
            apiClient.get<{ data: { meetings: Meeting[] } }>(
                `meetings?start_date=${startDate}&end_date=${endDate}${currentLanguage ? `&language=${currentLanguage}` : ''}`
            ),
    })

    const { data: statsData } = useQuery({
        queryKey: ['meetings-stats', startDate, endDate, currentLanguage],
        queryFn: () =>
            apiClient.get<{ data: { stats: MeetingStats } }>(
                `meetings/stats?start_date=${startDate}&end_date=${endDate}${currentLanguage ? `&language=${currentLanguage}` : ''}`
            ),
    })

    const cancelMutation = useMutation({
        mutationFn: (id: number) => apiClient.post(`meetings/${id}/cancel`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['meetings'] })
            queryClient.invalidateQueries({ queryKey: ['meetings-stats'] })
        },
    })

    const meetings: Meeting[] = meetingsData?.data?.meetings || []
    const stats = statsData?.data?.stats

    // ── Calendar grid days ───────────────────────────────────────────

    const calendarDays = useMemo(() => {
        const start = startOfWeek(monthStart, { weekStartsOn: 0 })
        const end = endOfWeek(monthEnd, { weekStartsOn: 0 })
        return eachDayOfInterval({ start, end })
    }, [currentMonth]) // eslint-disable-line react-hooks/exhaustive-deps

    // Group meetings by date string
    const meetingsByDate = useMemo(() => {
        const map: Record<string, Meeting[]> = {}
        for (const m of meetings) {
            const key = m.meeting_date // already yyyy-MM-dd
            if (!map[key]) map[key] = []
            map[key].push(m)
        }
        return map
    }, [meetings])

    // Meetings for the selected day
    const selectedDayMeetings = useMemo(() => {
        if (!selectedDay) return []
        const key = format(selectedDay, 'yyyy-MM-dd')
        return meetingsByDate[key] || []
    }, [selectedDay, meetingsByDate])

    // ── Table: filtered, sorted, paginated ───────────────────────────

    const filteredMeetings = useMemo(() => {
        let result = [...meetings]

        if (statusFilter) {
            result = result.filter((m) => m.status === statusFilter)
        }

        if (searchQuery.trim()) {
            result = result.filter((m) => meetingMatchesSearch(m, searchQuery.trim()))
        }

        result.sort((a, b) => {
            let cmp = 0
            switch (sortField) {
                case 'meeting_date':
                    cmp = a.meeting_date.localeCompare(b.meeting_date) || a.start_time.localeCompare(b.start_time)
                    break
                case 'start_time':
                    cmp = a.start_time.localeCompare(b.start_time)
                    break
                case 'customer_name':
                    cmp = (a.customer_name || '').localeCompare(b.customer_name || '', 'he')
                    break
                case 'customer_email':
                    cmp = (a.customer_email || '').localeCompare(b.customer_email || '')
                    break
                case 'customer_phone':
                    cmp = (a.customer_phone || '').localeCompare(b.customer_phone || '')
                    break
                case 'status':
                    cmp = a.status.localeCompare(b.status)
                    break
            }
            return sortDir === 'asc' ? cmp : -cmp
        })

        return result
    }, [meetings, statusFilter, searchQuery, sortField, sortDir])

    const totalPages = Math.max(1, Math.ceil(filteredMeetings.length / PAGE_SIZE))
    const pagedMeetings = filteredMeetings.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)

    // Reset page when filters change
    const handleStatusFilter = (v: string) => { setStatusFilter(v); setPage(0) }
    const handleSearch = (v: string) => { setSearchQuery(v); setPage(0) }

    // ── Sort toggle ──────────────────────────────────────────────────

    const toggleSort = useCallback((field: SortField) => {
        if (sortField === field) {
            setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))
        } else {
            setSortField(field)
            setSortDir('asc')
        }
        setPage(0)
    }, [sortField])

    // ── CSV Export ───────────────────────────────────────────────────

    const exportCsv = useCallback(() => {
        const header = [t('Date'), t('Start Time'), t('End Time'), t('Customer Name'), t('Phone'), t('Email'), t('Status'), t('Title'), t('Description'), t('AI Summary'), 'Google Meet', t('Created At')]
        const rows = filteredMeetings.map((m) => [
            m.meeting_date,
            formatTime(m.start_time),
            formatTime(m.end_time),
            m.customer_name,
            m.customer_phone,
            m.customer_email,
            getStatusConfig()[m.status]?.label || m.status,
            m.title,
            (m.description || '').replace(/\n/g, ' '),
            (m.ai_summary || '').replace(/\n/g, ' '),
            m.google_meet_link || '',
            m.created_at,
        ])

        const bom = '\uFEFF' // UTF-8 BOM for Excel Hebrew support
        const csv = bom + [header, ...rows].map((r) =>
            r.map((c) => {
                // Neutralize CSV formula injection: prefix a leading formula char with a quote
                const safe = /^[=+\-@\t\r]/.test(String(c)) ? "'" + String(c) : String(c)
                return `"${safe.replace(/"/g, '""')}"`
            }).join(',')
        ).join('\n')

        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `meetings-${startDate}-${endDate}.csv`
        a.click()
        URL.revokeObjectURL(url)
    }, [filteredMeetings, startDate, endDate])

    // ── Navigation ───────────────────────────────────────────────────

    const prevMonth = () => { setCurrentMonth((d) => subMonths(d, 1)); setSelectedDay(null) }
    const nextMonth = () => { setCurrentMonth((d) => addMonths(d, 1)); setSelectedDay(null) }

    const monthLabel = format(currentMonth, 'MMMM yyyy', { locale: dateLocale })

    // ── Render ───────────────────────────────────────────────────────

    if (isError) {
        return (
            <div className="p-6 text-center text-red-500">
                {t('Error loading meetings. Please try again.')}
            </div>
        )
    }

    return (
        <div className="space-y-6 animate-fade-in">
            <PageHeader title={t('Meetings')} subtitle={t('Meeting calendar, management and tracking')} />

            {/* ── Stats Cards ───────────────────────────────────────── */}
            {stats && (
                <div className="grid grid-cols-3 md:grid-cols-6 gap-3">
                    <StatCard label={t('Total')} value={stats.total} accent="border-gray-300" />
                    <StatCard label={t('Scheduled')} value={stats.scheduled} accent="border-blue-400" />
                    <StatCard label={t('Confirmed')} value={stats.confirmed} accent="border-green-400" />
                    <StatCard label={t('Completed')} value={stats.completed} accent="border-purple-400" />
                    <StatCard label={t('Cancelled')} value={stats.cancelled} accent="border-red-400" />
                    <StatCard label={t('No Show')} value={stats.no_show} accent="border-orange-400" />
                </div>
            )}

            {/* ── Calendar Grid ─────────────────────────────────────── */}
            <Card>
                {/* Month nav */}
                <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
                    {/* Pair icon+handler by reading direction: leading (start) button goes back,
                        trailing (end) button advances. Mirrored for RTL. */}
                    <button onClick={isRtl() ? nextMonth : prevMonth} className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                        {isRtl() ? <ChevronRight className="w-5 h-5" /> : <ChevronLeft className="w-5 h-5" />}
                    </button>
                    <h2 className="text-lg font-semibold text-gray-900 capitalize">{monthLabel}</h2>
                    <button onClick={isRtl() ? prevMonth : nextMonth} className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                        {isRtl() ? <ChevronLeft className="w-5 h-5" /> : <ChevronRight className="w-5 h-5" />}
                    </button>
                </div>

                {/* Day headers */}
                <div className="grid grid-cols-7 text-center text-xs font-medium text-gray-500 border-b border-gray-100">
                    {dayHeaders.map((d) => (
                        <div key={d} className="py-2">{d}</div>
                    ))}
                </div>

                {/* Day cells */}
                {isLoading ? (
                    <div className="flex items-center justify-center py-16 text-gray-400">
                        <CalendarIcon className="w-6 h-6 animate-pulse me-2" />
                        {t('Loading...')}
                    </div>
                ) : (
                    <div className="grid grid-cols-7">
                        {calendarDays.map((day) => {
                            const key = format(day, 'yyyy-MM-dd')
                            const dayMeetings = meetingsByDate[key] || []
                            const inMonth = isSameMonth(day, currentMonth)
                            const today = isToday(day)
                            const selected = selectedDay ? isSameDay(day, selectedDay) : false

                            return (
                                <button
                                    key={key}
                                    onClick={() => setSelectedDay(selected ? null : day)}
                                    className={`
                                        relative min-h-[72px] md:min-h-[88px] p-1.5 border-b border-e border-gray-100
                                        text-start transition-colors
                                        ${inMonth ? 'bg-white' : 'bg-gray-50'}
                                        ${selected ? 'ring-2 ring-primary-500 ring-inset z-10' : ''}
                                        ${dayMeetings.length > 0 && inMonth ? 'hover:bg-primary-50' : 'hover:bg-gray-50'}
                                    `}
                                >
                                    {/* Day number */}
                                    <span className={`
                                        inline-flex items-center justify-center w-7 h-7 rounded-full text-sm font-medium
                                        ${today ? 'bg-primary-600 text-white' : ''}
                                        ${!today && inMonth ? 'text-gray-800' : ''}
                                        ${!today && !inMonth ? 'text-gray-400' : ''}
                                    `}>
                                        {format(day, 'd')}
                                    </span>

                                    {/* Meeting indicators */}
                                    {dayMeetings.length > 0 && inMonth && (
                                        <div className="mt-0.5 space-y-0.5">
                                            {dayMeetings.slice(0, 2).map((m) => (
                                                <div
                                                    key={m.id}
                                                    className={`text-[10px] leading-tight px-1 py-0.5 rounded truncate ${getStatusConfig()[m.status]?.bg || 'bg-gray-100'} ${getStatusConfig()[m.status]?.color || 'text-gray-700'}`}
                                                >
                                                    {formatTime(m.start_time)} {m.customer_name?.split(' ')[0]}
                                                </div>
                                            ))}
                                            {dayMeetings.length > 2 && (
                                                <div className="text-[10px] text-gray-500 px-1">
                                                    {sprintf(t('+%s more'), dayMeetings.length - 2)}
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </button>
                            )
                        })}
                    </div>
                )}
            </Card>

            {/* ── Selected Day Panel ────────────────────────────────── */}
            {selectedDay && (
                <Card>
                    <CardHeader>
                        <div className="flex items-center justify-between">
                            <CardTitle className="flex items-center gap-2">
                                <CalendarIcon className="w-5 h-5 text-primary-600" />
                                {formatDateLocalized(format(selectedDay, 'yyyy-MM-dd'), dateLocale)}
                            </CardTitle>
                            <button
                                onClick={() => setSelectedDay(null)}
                                className="p-1 hover:bg-gray-100 rounded-lg"
                            >
                                <X className="w-4 h-4 text-gray-400" />
                            </button>
                        </div>
                    </CardHeader>
                    <CardContent>
                        {selectedDayMeetings.length === 0 ? (
                            <p className="text-center py-6 text-gray-400">{t('No meetings on this day')}</p>
                        ) : (
                            <div className="space-y-3">
                                {selectedDayMeetings.map((m) => (
                                    <MeetingCard
                                        key={m.id}
                                        meeting={m}
                                        expanded={expandedMeetingId === m.id}
                                        onToggle={() => setExpandedMeetingId(expandedMeetingId === m.id ? null : m.id)}
                                        onCancel={() => cancelMutation.mutate(m.id)}
                                        isCancelling={cancelMutation.isPending}
                                        dateLocale={dateLocale}
                                    />
                                ))}
                            </div>
                        )}
                    </CardContent>
                </Card>
            )}

            {/* ── Meetings Table ─────────────────────────────────────── */}
            <Card>
                <CardHeader>
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-3">
                        <CardTitle>{t('All Meetings')}</CardTitle>
                        <div className="flex flex-wrap items-center gap-2">
                            {/* Search */}
                            <div className="relative">
                                <Search className="w-4 h-4 absolute start-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                <input
                                    type="text"
                                    placeholder={t('Search...')}
                                    value={searchQuery}
                                    onChange={(e) => handleSearch(e.target.value)}
                                    className="ps-9 pe-3 py-2 text-sm border border-gray-200 rounded-lg w-48 focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                />
                            </div>

                            {/* Status filter */}
                            <div className="relative">
                                <Filter className="w-4 h-4 absolute start-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
                                <select
                                    value={statusFilter}
                                    onChange={(e) => handleStatusFilter(e.target.value)}
                                    className="ps-9 pe-3 py-2 text-sm border border-gray-200 rounded-lg appearance-none bg-white focus:ring-2 focus:ring-primary-500"
                                >
                                    {getStatusOptions().map((o) => (
                                        <option key={o.value} value={o.value}>{o.label}</option>
                                    ))}
                                </select>
                            </div>

                            {/* CSV export */}
                            <button
                                onClick={exportCsv}
                                className="flex items-center gap-1.5 px-3 py-2 text-sm bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
                            >
                                <Download className="w-4 h-4" />
                                {t('Export CSV')}
                            </button>
                        </div>
                    </div>
                </CardHeader>

                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-gray-200 bg-gray-50 text-gray-600">
                                <SortHeader label={t('Date')} field="meeting_date" current={sortField} dir={sortDir} onSort={toggleSort} />
                                <SortHeader label={t('Time')} field="start_time" current={sortField} dir={sortDir} onSort={toggleSort} />
                                <SortHeader label={t('Customer Name')} field="customer_name" current={sortField} dir={sortDir} onSort={toggleSort} />
                                <SortHeader label={t('Phone')} field="customer_phone" current={sortField} dir={sortDir} onSort={toggleSort} />
                                <SortHeader label={t('Email')} field="customer_email" current={sortField} dir={sortDir} onSort={toggleSort} />
                                <SortHeader label={t('Status')} field="status" current={sortField} dir={sortDir} onSort={toggleSort} />
                                <th className="px-4 py-3 text-start font-medium">{t('Source')}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {pagedMeetings.length === 0 ? (
                                <tr>
                                    <td colSpan={7} className="text-center py-10 text-gray-400">
                                        <CalendarIcon className="w-8 h-8 mx-auto mb-2 opacity-40" />
                                        {searchQuery || statusFilter ? t('No results found') : t('No meetings this month')}
                                    </td>
                                </tr>
                            ) : (
                                pagedMeetings.map((m) => {
                                    const cfg = getStatusConfig()[m.status]
                                    const cf = parseCustomFields(m.custom_fields)
                                    return (
                                        <tr
                                            key={m.id}
                                            className="border-b border-gray-100 hover:bg-gray-50 transition-colors cursor-pointer"
                                            onClick={() => {
                                                const day = new Date(m.meeting_date + 'T00:00:00')
                                                setSelectedDay(day)
                                                setExpandedMeetingId(m.id)
                                            }}
                                        >
                                            <td className="px-4 py-3 whitespace-nowrap font-medium text-gray-900">
                                                {format(new Date(m.meeting_date + 'T00:00:00'), 'dd/MM/yyyy')}
                                            </td>
                                            <td className="px-4 py-3 whitespace-nowrap text-gray-700">
                                                {formatTime(m.start_time)} - {formatTime(m.end_time)}
                                            </td>
                                            <td className="px-4 py-3 text-gray-900">{m.customer_name}</td>
                                            <td className="px-4 py-3 text-gray-700 font-mono text-xs" dir="ltr">{m.customer_phone}</td>
                                            <td className="px-4 py-3 text-gray-700 truncate max-w-[180px]">{m.customer_email}</td>
                                            <td className="px-4 py-3">
                                                <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${cfg?.bg} ${cfg?.color}`}>
                                                    <span className={`w-1.5 h-1.5 rounded-full ${cfg?.dot}`} />
                                                    {cfg?.label}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3 text-gray-500 truncate max-w-[140px]">
                                                {cf.page_title || cf.page_url ? (
                                                    <span className="flex items-center gap-1">
                                                        <Globe className="w-3 h-3 flex-shrink-0" />
                                                        {cf.page_title || safeHostname(cf.page_url)}
                                                    </span>
                                                ) : (
                                                    <span className="text-gray-300">-</span>
                                                )}
                                            </td>
                                        </tr>
                                    )
                                })
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Pagination */}
                {totalPages > 1 && (
                    <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100 text-sm text-gray-600">
                        <span>
                            {sprintf(t('%s meetings · Page %s of %s'), filteredMeetings.length, page + 1, totalPages)}
                        </span>
                        <div className="flex gap-1">
                            <button
                                onClick={() => setPage((p) => Math.max(0, p - 1))}
                                disabled={page === 0}
                                className="px-3 py-1 rounded border border-gray-200 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                {t('Previous')}
                            </button>
                            <button
                                onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
                                disabled={page >= totalPages - 1}
                                className="px-3 py-1 rounded border border-gray-200 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
                            >
                                {t('Next')}
                            </button>
                        </div>
                    </div>
                )}
            </Card>
        </div>
    )
}

// ── Sub-components ───────────────────────────────────────────────────

function StatCard({ label, value, accent }: { label: string; value: number; accent: string }) {
    return (
        <div className={`bg-white rounded-xl border-t-4 ${accent} shadow-sm p-4 text-center`}>
            <div className="text-2xl font-bold text-gray-900">{value}</div>
            <div className="text-xs text-gray-500 mt-1">{label}</div>
        </div>
    )
}

function SortHeader({ label, field, current, dir, onSort }: {
    label: string
    field: SortField
    current: SortField
    dir: SortDir
    onSort: (f: SortField) => void
}) {
    const active = current === field
    return (
        <th
            className="px-4 py-3 text-start font-medium cursor-pointer select-none hover:text-gray-900 transition-colors"
            onClick={() => onSort(field)}
        >
            <span className="inline-flex items-center gap-1">
                {label}
                {active && (
                    dir === 'asc'
                        ? <ChevronUp className="w-3.5 h-3.5" />
                        : <ChevronDown className="w-3.5 h-3.5" />
                )}
            </span>
        </th>
    )
}

/** Expandable meeting card shown for a selected day. */
function MeetingCard({ meeting, expanded, onToggle, onCancel, isCancelling, dateLocale }: {
    meeting: Meeting
    expanded: boolean
    onToggle: () => void
    onCancel: () => void
    isCancelling: boolean
    dateLocale: Locale
}) {
    const cfg = getStatusConfig()[meeting.status]
    const customFields = parseCustomFields(meeting.custom_fields)

    return (
        <div className={`border rounded-xl overflow-hidden transition-all ${expanded ? 'border-primary-300 shadow-md' : 'border-gray-200 shadow-sm'}`}>
            {/* Summary row (always visible) */}
            <button
                onClick={onToggle}
                className="w-full flex items-center gap-3 p-4 text-start hover:bg-gray-50 transition-colors"
            >
                {/* Time badge */}
                <div className="flex-shrink-0 w-16 text-center">
                    <div className="text-sm font-bold text-gray-900">{formatTime(meeting.start_time)}</div>
                    <div className="text-xs text-gray-500">{formatTime(meeting.end_time)}</div>
                </div>

                {/* Core info */}
                <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                        <span className="font-semibold text-gray-900 truncate">{meeting.customer_name}</span>
                        <span className={`px-2 py-0.5 text-[11px] rounded-full font-medium ${cfg?.bg} ${cfg?.color}`}>
                            {cfg?.label}
                        </span>
                    </div>
                    <div className="flex items-center gap-3 text-xs text-gray-500">
                        {meeting.customer_phone && (
                            <span className="flex items-center gap-1">
                                <Phone className="w-3 h-3" />
                                <span dir="ltr">{meeting.customer_phone}</span>
                            </span>
                        )}
                        {meeting.customer_email && (
                            <span className="flex items-center gap-1 truncate">
                                <Mail className="w-3 h-3" />
                                {meeting.customer_email}
                            </span>
                        )}
                    </div>
                </div>

                {/* Meet / Calendar icons */}
                <div className="flex items-center gap-2 flex-shrink-0">
                    {meeting.google_meet_link && (
                        <Video className="w-4 h-4 text-blue-500" />
                    )}
                    {meeting.google_calendar_link && (
                        <CalendarIcon className="w-4 h-4 text-green-500" />
                    )}
                    {expanded
                        ? <ChevronUp className="w-4 h-4 text-gray-400" />
                        : <ChevronDown className="w-4 h-4 text-gray-400" />
                    }
                </div>
            </button>

            {/* Expanded details */}
            {expanded && (
                <div className="border-t border-gray-100 px-4 pb-4 space-y-4 bg-gray-50/50">
                    {/* Title */}
                    <div className="pt-4">
                        <h4 className="text-sm font-medium text-gray-700">{meeting.title}</h4>
                    </div>

                    {/* Customer details */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <DetailItem icon={User} label={t('Name')} value={meeting.customer_name} />
                        <DetailItem icon={Phone} label={t('Phone')} value={meeting.customer_phone} dir="ltr" />
                        <DetailItem icon={Mail} label={t('Email')} value={meeting.customer_email} href={`mailto:${meeting.customer_email}`} />
                    </div>

                    {/* Date & time */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <DetailItem
                            icon={CalendarIcon}
                            label={t('Date')}
                            value={formatDateLocalized(meeting.meeting_date, dateLocale)}
                        />
                        <DetailItem
                            icon={Clock}
                            label={t('Time')}
                            value={`${formatTime(meeting.start_time)} - ${formatTime(meeting.end_time)}`}
                        />
                    </div>

                    {/* Google links */}
                    {(meeting.google_meet_link || meeting.google_calendar_link) && (
                        <div className="flex flex-wrap gap-2">
                            {meeting.google_meet_link && (
                                <a
                                    href={meeting.google_meet_link}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    onClick={(e) => e.stopPropagation()}
                                    className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                                >
                                    <Video className="w-4 h-4" />
                                    Google Meet
                                    <ExternalLink className="w-3 h-3" />
                                </a>
                            )}
                            {meeting.google_calendar_link && (
                                <a
                                    href={meeting.google_calendar_link}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    onClick={(e) => e.stopPropagation()}
                                    className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                                >
                                    <CalendarIcon className="w-4 h-4" />
                                    {t('View in Calendar')}
                                    <ExternalLink className="w-3 h-3" />
                                </a>
                            )}
                        </div>
                    )}

                    {/* Description */}
                    {meeting.description && (
                        <div className="bg-white rounded-lg border border-gray-200 p-3">
                            <h5 className="text-xs font-medium text-gray-500 mb-1">{t('Description')}</h5>
                            <p className="text-sm text-gray-700 whitespace-pre-line">{meeting.description}</p>
                        </div>
                    )}

                    {/* AI summary */}
                    {meeting.ai_summary && (
                        <div className="bg-purple-50 rounded-lg border border-purple-200 p-3">
                            <div className="flex items-center gap-2 mb-1">
                                <FileText className="w-3.5 h-3.5 text-purple-600" />
                                <h5 className="text-xs font-medium text-purple-600">{t('Conversation Summary (AI)')}</h5>
                            </div>
                            <p className="text-sm text-purple-900 whitespace-pre-line">{meeting.ai_summary}</p>
                        </div>
                    )}

                    {/* Link to conversation */}
                    {meeting.conversation_db_id && (
                        <div className="flex items-center gap-2">
                            <MessageSquare className="w-3.5 h-3.5 text-primary-500" />
                            <Link
                                to={`/conversations/${meeting.conversation_db_id}`}
                                className="text-sm text-primary-600 hover:underline flex items-center gap-1"
                                onClick={(e) => e.stopPropagation()}
                            >
                                {t('View original conversation')}
                                <ExternalLink className="w-3 h-3" />
                            </Link>
                        </div>
                    )}

                    {/* Custom fields / source page */}
                    {(customFields.page_url || customFields.page_title) && (
                        <div className="flex items-center gap-2 text-xs text-gray-500">
                            <Globe className="w-3.5 h-3.5" />
                            <span>{t('Source')}:</span>
                            {customFields.page_url ? (
                                <a href={customFields.page_url} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline truncate">
                                    {customFields.page_title || customFields.page_url}
                                </a>
                            ) : (
                                <span>{customFields.page_title}</span>
                            )}
                        </div>
                    )}

                    {/* Created at */}
                    <div className="text-xs text-gray-400">
                        {sprintf(t('Created: %s'), meeting.created_at ? format(new Date(meeting.created_at), 'dd/MM/yyyy HH:mm') : '-')}
                    </div>

                    {/* Actions */}
                    {meeting.status !== 'cancelled' && meeting.status !== 'completed' && (
                        <div className="flex justify-end pt-1">
                            <button
                                onClick={(e) => { e.stopPropagation(); onCancel() }}
                                disabled={isCancelling}
                                className="px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
                            >
                                {isCancelling ? t('Cancelling...') : t('Cancel Meeting')}
                            </button>
                        </div>
                    )}
                </div>
            )}
        </div>
    )
}

function DetailItem({ icon: Icon, label, value, href, dir }: {
    icon: typeof User
    label: string
    value: string
    href?: string
    dir?: string
}) {
    if (!value) return null
    return (
        <div className="flex items-start gap-2 text-sm">
            <Icon className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
            <div>
                <div className="text-xs text-gray-500">{label}</div>
                {href ? (
                    <a href={href} className="text-primary-600 hover:underline" dir={dir}>{value}</a>
                ) : (
                    <span className="text-gray-800" dir={dir}>{value}</span>
                )}
            </div>
        </div>
    )
}

export default Meetings
