'use client';

import React, { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { App, Button, DatePicker, Empty, Form, Input, Modal, Popconfirm, Segmented, Select, Spin, Tag, TimePicker } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { PageHeader } from '../platform/PlatformPrimitives';
import { leadsApi, type DirectoryUser } from '../../lib/leads';
import { dealsApi } from '../../lib/deals';
import { accountsApi } from '../../lib/accounts';
import { type CalendarEventRecord, type CalendarEventType, calendarApi } from '../../lib/calendar';
import { useCrmOptions } from '../../lib/options';
import { useAuth, UserRole } from '../../context/AuthContext';

type RelatedType = 'lead' | 'deal' | 'account';

const RELATED_LABELS: Record<RelatedType, string> = { lead: 'Lead', deal: 'Deal', account: 'Customer' };

const EVENT_COLOR_MAP: Record<CalendarEventType, string> = {
  Meeting: '#0E7C66', // teal / primary
  Demo: '#4F46E5', // indigo
  Call: '#2563EB', // blue
  'Follow-up': '#D97706', // amber
  Internal: '#64748B', // gray
};

export function CalendarView() {
  const { calendarEventTypes } = useCrmOptions();
  const { message } = App.useApp();
  const { user } = useAuth();
  const [currentDate, setCurrentDate] = useState(dayjs());
  const [formInitialValues, setFormInitialValues] = useState<Record<string, unknown>>({});
  const [mode, setMode] = useState<'month' | 'agenda'>('month');
  const [loading, setLoading] = useState(true);
  const [events, setEvents] = useState<CalendarEventRecord[]>([]);
  const [upcoming, setUpcoming] = useState<CalendarEventRecord[]>([]);

  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [editingEvent, setEditingEvent] = useState<CalendarEventRecord | null>(null);
  const [selectedEvent, setSelectedEvent] = useState<CalendarEventRecord | null>(null);
  const [relatedType, setRelatedType] = useState<RelatedType | undefined>(undefined);
  const [relatedOptions, setRelatedOptions] = useState<Array<{ value: string; label: string }>>([]);
  const [loadingRelated, setLoadingRelated] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [reload, setReload] = useState(0);
  const [people, setPeople] = useState<DirectoryUser[]>([]);
  const [ownerFilter, setOwnerFilter] = useState<string | undefined>(undefined);
  const [form] = Form.useForm();

  const year = currentDate.year();
  const month = currentDate.month(); // 0-11

  useEffect(() => {
    let active = true;
    const load = async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const res = await calendarApi.list({ year, month, ownerId: ownerFilter });
        if (!active) return;
        setEvents(res.data);
        setUpcoming(res.upcoming);
      } catch (err) {
        if (!active) return;
        message.error(err instanceof Error ? err.message : 'Failed to load calendar');
      } finally {
        if (active) setLoading(false);
      }
    };
    void load();
    return () => {
      active = false;
    };
  }, [year, month, ownerFilter, reload, message]);

  useEffect(() => {
    leadsApi
      .directory()
      .then(setPeople)
      .catch(() => setPeople([]));
  }, []);

  const handlePrevMonth = () => setCurrentDate((d) => d.subtract(1, 'month'));
  const handleNextMonth = () => setCurrentDate((d) => d.add(1, 'month'));
  const handleToday = () => setCurrentDate(dayjs());

  const fetchRelatedOptions = async (type?: RelatedType) => {
    if (!type) {
      setRelatedOptions([]);
      return;
    }
    setLoadingRelated(true);
    try {
      if (type === 'lead') {
        const res = await leadsApi.list({ view: 'all', pageSize: 100 });
        setRelatedOptions(
          res.items.map((l) => ({
            value: l.id,
            label: l.company ? `${l.name} (${l.company})` : l.name,
          })),
        );
      } else if (type === 'deal') {
        const res = await dealsApi.list({ view: 'all', pageSize: 100 });
        setRelatedOptions(
          res.items.map((d) => ({
            value: d.id,
            label: `${d.dealNumber} · ${d.title}`,
          })),
        );
      } else if (type === 'account') {
        const res = await accountsApi.options();
        setRelatedOptions(
          res.map((a) => ({
            value: a.id,
            label: a.city ? `${a.name} (${a.city})` : a.name,
          })),
        );
      }
    } catch {
      setRelatedOptions([]);
    } finally {
      setLoadingRelated(false);
    }
  };

  const handleOpenCreate = (presetDate?: dayjs.Dayjs) => {
    setEditingEvent(null);
    setRelatedType(undefined);
    setRelatedOptions([]);
    setFormInitialValues({
      type: 'Meeting',
      durationMinutes: 30,
      date: presetDate || dayjs(),
      startTime: dayjs('10:00', 'HH:mm'),
      ownerId: user?.id,
      attendeeIds: user?.id ? [user.id] : [],
      externalGuest: '',
    });
    setCreateModalOpen(true);
  };

  const handleOpenEdit = (ev: CalendarEventRecord) => {
    setEditingEvent(ev);
    setSelectedEvent(null);
    let relType: RelatedType | undefined;
    let relId: string | undefined;
    if (ev.leadId) {
      relType = 'lead';
      relId = ev.leadId;
    } else if (ev.dealId) {
      relType = 'deal';
      relId = ev.dealId;
    } else if (ev.accountId) {
      relType = 'account';
      relId = ev.accountId;
    }
    setRelatedType(relType);
    if (relType) {
      void fetchRelatedOptions(relType);
    } else {
      setRelatedOptions([]);
    }

    const attendeeIds: string[] = [];
    let externalGuest = ev.withWhom || '';
    if (ev.withWhom) {
      const parts = ev.withWhom.split(',').map((s) => s.trim());
      const remaining: string[] = [];
      parts.forEach((part) => {
        const found = people.find((p) => p.name.toLowerCase() === part.toLowerCase());
        if (found) {
          attendeeIds.push(found.id);
        } else {
          remaining.push(part);
        }
      });
      externalGuest = remaining.join(', ');
    }

    setFormInitialValues({
      title: ev.title,
      type: ev.type,
      date: dayjs(ev.date),
      startTime: dayjs(ev.startTime, 'HH:mm'),
      durationMinutes: ev.durationMinutes,
      attendeeIds,
      externalGuest,
      description: ev.description ?? undefined,
      ownerId: ev.ownerId ?? undefined,
      relatedType: relType,
      relatedId: relId,
    });
    setCreateModalOpen(true);
  };

  const handleSubmit = async (values: { title: string; type: CalendarEventType; date: dayjs.Dayjs; startTime: dayjs.Dayjs; durationMinutes: number; attendeeIds?: string[]; externalGuest?: string; description?: string; ownerId?: string; relatedType?: RelatedType; relatedId?: string }) => {
    setSubmitting(true);
    try {
      const attendeeNames = (values.attendeeIds || []).map((id) => people.find((p) => p.id === id)?.name).filter(Boolean);
      const withWhom = [...attendeeNames, values.externalGuest ? values.externalGuest.trim() : null].filter(Boolean).join(', ');

      const links: {
        leadId?: string;
        dealId?: string;
        accountId?: string;
      } = {};
      if (values.relatedType && values.relatedId?.trim()) {
        const id = values.relatedId.trim();
        if (values.relatedType === 'lead') links.leadId = id;
        if (values.relatedType === 'deal') links.dealId = id;
        if (values.relatedType === 'account') links.accountId = id;
      }

      if (editingEvent) {
        const original = editingEvent.leadId ? `lead:${editingEvent.leadId}` : editingEvent.dealId ? `deal:${editingEvent.dealId}` : editingEvent.accountId ? `account:${editingEvent.accountId}` : '';
        const chosen = values.relatedType && values.relatedId ? `${values.relatedType}:${values.relatedId}` : '';
        const linkChanges = original === chosen ? {} : { leadId: null, dealId: null, accountId: null, ...links };
        await calendarApi.update(editingEvent.id, {
          title: values.title,
          type: values.type,
          date: values.date.toISOString(),
          startTime: values.startTime.format('HH:mm'),
          durationMinutes: values.durationMinutes,
          withWhom: withWhom || '',
          description: values.description ?? '',
          ownerId: values.ownerId,
          ...linkChanges,
        });
        message.success('Event updated');
      } else {
        await calendarApi.create({
          title: values.title,
          type: values.type,
          date: values.date.toISOString(),
          startTime: values.startTime.format('HH:mm'),
          durationMinutes: values.durationMinutes,
          withWhom: withWhom || undefined,
          description: values.description,
          ownerId: values.ownerId,
          ...links,
        });
        message.success('Event scheduled');
      }
      setCreateModalOpen(false);
      setEditingEvent(null);
      form.resetFields();
      setReload((n) => n + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to save event');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await calendarApi.delete(id);
      message.success('Event deleted');
      setSelectedEvent(null);
      setReload((n) => n + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to delete event');
    }
  };

  // Group events by YYYY-MM-DD
  const eventsByDay = useMemo(() => {
    const map = new Map<string, CalendarEventRecord[]>();
    events.forEach((e) => {
      const key = dayjs(e.date).format('YYYY-MM-DD');
      const list = map.get(key) || [];
      list.push(e);
      map.set(key, list);
    });
    return map;
  }, [events]);

  // Generate 42 calendar grid cells (Monday start)
  const calendarCells = useMemo(() => {
    const firstDay = currentDate.startOf('month');
    // Day of week: 0 = Sunday, 1 = Monday, ...
    const dayOfWeek = (firstDay.day() + 6) % 7; // Convert to Monday = 0
    const gridStart = firstDay.subtract(dayOfWeek, 'day');

    const cells: dayjs.Dayjs[] = [];
    for (let i = 0; i < 42; i++) {
      cells.push(gridStart.add(i, 'day'));
    }
    return cells;
  }, [currentDate]);

  return (
    <div>
      <PageHeader
        eyebrow="Productivity"
        title="Calendar"
        subtitle="Schedule and coordinate client meetings, team appointments, and sales milestones."
        actions={
          <div className="flex flex-wrap items-center gap-2">
            <Select allowClear placeholder="All owners" value={ownerFilter} onChange={setOwnerFilter} className="min-w-[160px]" aria-label="Filter by owner" options={people.map((p) => ({ value: p.id, label: p.id === user?.id ? `${p.name} (me)` : p.name }))} />
            <Button type="primary" icon={<Icon name="plus" size={15} />} onClick={() => handleOpenCreate()}>
              New event
            </Button>
          </div>
        }
      />

      <div className="mt-4 grid grid-cols-1 gap-6 lg:grid-cols-4">
        {/* Main Calendar View (3 columns) */}
        <div className="lg:col-span-3 rounded-card border border-[var(--tcx-border)] bg-[var(--tcx-surface)] shadow-sm overflow-hidden flex flex-col">
          {/* Calendar Navigation Bar */}
          <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--tcx-border)] px-4 py-3">
            <div className="flex items-center gap-3">
              <h2 className="text-base font-semibold text-[var(--tcx-text)]">{currentDate.format('MMMM YYYY')}</h2>
              <div className="flex items-center gap-1">
                <Button size="small" aria-label="Previous month" icon={<Icon name="chevronDown" size={14} className="rotate-90" />} onClick={handlePrevMonth} />
                <Button size="small" onClick={handleToday}>
                  Today
                </Button>
                <Button size="small" aria-label="Next month" icon={<Icon name="chevronDown" size={14} className="-rotate-90" />} onClick={handleNextMonth} />
              </div>
            </div>

            <Segmented
              value={mode}
              onChange={(v) => setMode(v as 'month' | 'agenda')}
              options={[
                { label: 'Month', value: 'month' },
                { label: 'Agenda', value: 'agenda' },
              ]}
            />
          </div>

          {loading ? (
            <div className="flex flex-1 items-center justify-center p-12">
              <Spin />
            </div>
          ) : mode === 'month' ? (
            /* Month Grid View */
            <div className="flex-1">
              <div className="grid grid-cols-7 border-b border-[var(--tcx-border)] bg-[var(--tcx-bg)] text-center text-[12px] font-semibold text-[var(--tcx-muted)] py-2">
                <div>Mon</div>
                <div>Tue</div>
                <div>Wed</div>
                <div>Thu</div>
                <div>Fri</div>
                <div>Sat</div>
                <div>Sun</div>
              </div>

              <div className="grid grid-cols-7 auto-rows-fr">
                {calendarCells.map((d, i) => {
                  const key = d.format('YYYY-MM-DD');
                  const dayEvents = eventsByDay.get(key) || [];
                  const isCurrentMonth = d.month() === month;
                  const isToday = d.isSame(dayjs(), 'day');

                  return (
                    <div key={i} onClick={() => handleOpenCreate(d)} className={`min-h-[92px] border-b border-r border-[var(--tcx-border)] p-1.5 transition-colors cursor-pointer hover:bg-[var(--tcx-bg)] ${!isCurrentMonth ? 'opacity-40 bg-[var(--tcx-bg)]/40' : ''} ${isToday ? 'bg-emerald-50/30 dark:bg-emerald-950/20' : ''}`}>
                      <div className="flex items-center justify-between mb-1">
                        <span className={`flex h-5 w-5 items-center justify-center rounded-full text-[12px] font-medium ${isToday ? 'bg-[var(--tcx-primary)] text-white' : 'text-[var(--tcx-text)]'}`}>{d.date()}</span>
                        {dayEvents.length > 2 && <span className="text-[10.5px] text-[var(--tcx-muted)] font-medium">+{dayEvents.length - 2}</span>}
                      </div>

                      <div className="space-y-1">
                        {dayEvents.slice(0, 2).map((ev) => (
                          <div
                            key={ev.id}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSelectedEvent(ev);
                            }}
                            style={{
                              borderLeftColor: EVENT_COLOR_MAP[ev.type] || '#0E7C66',
                            }}
                            className="truncate rounded border-l-2 bg-[var(--tcx-bg)] px-1.5 py-0.5 text-[11px] font-medium text-[var(--tcx-text)] shadow-xs transition-opacity hover:opacity-80"
                          >
                            <span className="font-semibold text-[10px] mr-1 tabular-nums">{ev.startTime}</span>
                            {ev.title}
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ) : (
            /* Agenda List View */
            <div className="flex-1 p-4 divide-y divide-[var(--tcx-border)]">
              {events.length === 0 ? (
                <div className="p-8 text-center">
                  <Empty description="No events scheduled for this month" />
                </div>
              ) : (
                events.map((ev) => (
                  <div key={ev.id} onClick={() => setSelectedEvent(ev)} className="flex items-center justify-between py-3 cursor-pointer hover:bg-[var(--tcx-bg)] px-2 rounded-lg transition-colors">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-1.5 rounded-full" style={{ background: EVENT_COLOR_MAP[ev.type] }} />
                      <div>
                        <div className="text-[13.5px] font-medium text-[var(--tcx-text)]">{ev.title}</div>
                        <div className="text-[12px] text-[var(--tcx-muted)]">
                          {dayjs(ev.date).format('ddd, D MMM')} · {ev.startTime} ({ev.durationMinutes} min)
                          {ev.withWhom ? ` · With ${ev.withWhom}` : ''}
                        </div>
                      </div>
                    </div>

                    <Tag
                      style={{
                        color: EVENT_COLOR_MAP[ev.type],
                        borderColor: `${EVENT_COLOR_MAP[ev.type]}40`,
                        background: `${EVENT_COLOR_MAP[ev.type]}15`,
                      }}
                      className="font-medium"
                    >
                      {ev.type}
                    </Tag>
                  </div>
                ))
              )}
            </div>
          )}
        </div>

        {/* Sidebar: Upcoming Events & Legend */}
        <div className="space-y-4">
          <div className="rounded-card border border-[var(--tcx-border)] bg-[var(--tcx-surface)] p-4 shadow-sm">
            <h3 className="text-sm font-semibold text-[var(--tcx-text)] mb-3">Coming up</h3>
            {upcoming.length === 0 ? (
              <p className="text-xs text-[var(--tcx-muted)]">No upcoming events</p>
            ) : (
              <div className="space-y-3">
                {upcoming.map((ev) => (
                  <div key={ev.id} onClick={() => setSelectedEvent(ev)} className="flex items-start gap-2.5 cursor-pointer hover:opacity-80 transition-opacity">
                    <div className="mt-1 h-2 w-2 rounded-full flex-none" style={{ background: EVENT_COLOR_MAP[ev.type] }} />
                    <div className="min-w-0 flex-1">
                      <div className="text-[12.5px] font-medium text-[var(--tcx-text)] truncate">{ev.title}</div>
                      <div className="text-[11px] text-[var(--tcx-muted)] tabular-nums">
                        {dayjs(ev.date).format('D MMM')}, {ev.startTime}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <div className="mt-6 border-t border-[var(--tcx-border)] pt-4">
              <h4 className="text-[11.5px] font-semibold text-[var(--tcx-muted)] uppercase tracking-wider mb-2">Event Types</h4>
              <div className="grid grid-cols-2 gap-2 text-xs">
                {calendarEventTypes.map((t: CalendarEventType) => (
                  <div key={t} className="flex items-center gap-1.5">
                    <span className="h-2 w-2 rounded-full" style={{ background: EVENT_COLOR_MAP[t] }} />
                    <span className="text-[12px] text-[var(--tcx-text)]">{t}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Schedule / Edit Event Modal */}
      {createModalOpen && (
        <Modal
          title={editingEvent ? 'Edit Event' : 'Schedule Event'}
          open={createModalOpen}
          width={680}
          centered
          onCancel={() => {
            setCreateModalOpen(false);
            setEditingEvent(null);
          }}
          destroyOnHidden
          footer={
            <div className="flex items-center justify-end gap-2 border-t border-[var(--tcx-border)] pt-3">
              <Button
                onClick={() => {
                  setCreateModalOpen(false);
                  setEditingEvent(null);
                }}
              >
                Cancel
              </Button>
              <Button type="primary" loading={submitting} onClick={() => form.submit()}>
                {editingEvent ? 'Save Changes' : 'Schedule Event'}
              </Button>
            </div>
          }
        >
          <Form preserve={false} form={form} layout="vertical" onFinish={handleSubmit} initialValues={formInitialValues} className="mt-3">
            <Form.Item name="title" label="Event Title" rules={[{ required: true, message: 'Please enter event title' }]}>
              <Input placeholder="Enter event title" />
            </Form.Item>

            <div className="grid grid-cols-2 gap-4">
              <Form.Item name="relatedType" label="Related to (Optional)">
                <Select
                  allowClear
                  placeholder="Select record type"
                  onChange={(val) => {
                    setRelatedType(val);
                    form.setFieldValue('relatedId', undefined);
                    void fetchRelatedOptions(val);
                  }}
                  options={[
                    { value: 'lead', label: 'Lead' },
                    { value: 'deal', label: 'Deal' },
                    { value: 'account', label: 'Customer' },
                  ]}
                />
              </Form.Item>
              <Form.Item name="relatedId" label={relatedType ? RELATED_LABELS[relatedType] : 'Record'}>
                <Select
                  showSearch
                  allowClear
                  disabled={!relatedType}
                  placeholder={!relatedType ? 'Choose type first' : loadingRelated ? 'Loading...' : `Search ${RELATED_LABELS[relatedType].toLowerCase()}...`}
                  filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                  notFoundContent={
                    loadingRelated ? (
                      <div className="p-2 text-center">
                        <Spin size="small" />
                      </div>
                    ) : null
                  }
                  options={relatedOptions}
                />
              </Form.Item>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Form.Item name="type" label="Type" rules={[{ required: true }]}>
                <Select
                  options={calendarEventTypes.map((t: CalendarEventType) => ({
                    value: t,
                    label: t,
                  }))}
                />
              </Form.Item>

              <Form.Item name="durationMinutes" label="Duration" rules={[{ required: true }]}>
                <Select
                  options={[
                    { value: 15, label: '15 minutes' },
                    { value: 30, label: '30 minutes' },
                    { value: 45, label: '45 minutes' },
                    { value: 60, label: '1 hour' },
                    { value: 90, label: '1.5 hours' },
                    { value: 120, label: '2 hours' },
                  ]}
                />
              </Form.Item>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Form.Item name="date" label="Date" rules={[{ required: true, message: 'Pick a date' }]}>
                <DatePicker className="w-full" />
              </Form.Item>

              <Form.Item name="startTime" label="Start Time" rules={[{ required: true, message: 'Pick a start time' }]}>
                <TimePicker format="HH:mm" className="w-full" />
              </Form.Item>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Form.Item name="ownerId" label="Event Host / Organizer" rules={[{ required: true, message: 'Choose organizer' }]}>
                <Select showSearch optionFilterProp="label" options={people.map((p) => ({ value: p.id, label: p.name }))} />
              </Form.Item>

              <Form.Item name="externalGuest" label="Client / External Guest (Optional)">
                <Input placeholder="Enter client name or email address" />
              </Form.Item>
            </div>

            <Form.Item name="attendeeIds" label="Team Attendees (Users)">
              <Select mode="multiple" placeholder="Select team members attending..." options={people.map((p) => ({ value: p.id, label: p.name }))} showSearch optionFilterProp="label" />
            </Form.Item>

            <Form.Item name="description" label="Meeting Agenda / Notes" className="mb-0">
              <Input.TextArea rows={2} placeholder="Enter meeting agenda, notes, or video link" />
            </Form.Item>
          </Form>
        </Modal>
      )}

      {/* View Event Detail Modal */}
      <Modal
        title={selectedEvent?.title}
        open={selectedEvent !== null}
        onCancel={() => setSelectedEvent(null)}
        footer={
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Button icon={<Icon name="edit" size={14} />} onClick={() => selectedEvent && handleOpenEdit(selectedEvent)}>
                Edit
              </Button>
              {(user?.role === UserRole.ORGANIZATION_ADMIN || user?.canDelete) && (
                <Popconfirm title="Delete this event?" onConfirm={() => selectedEvent && void handleDelete(selectedEvent.id)} okText="Delete" cancelText="Cancel">
                  <Button danger type="text" icon={<Icon name="trash" size={14} />}>
                    Delete
                  </Button>
                </Popconfirm>
              )}
            </div>
            <Button onClick={() => setSelectedEvent(null)}>Close</Button>
          </div>
        }
      >
        {selectedEvent && (
          <div className="space-y-3 py-2 text-sm">
            <div className="flex items-center justify-between">
              <span className="text-[var(--tcx-muted)]">Type</span>
              <Tag
                style={{
                  color: EVENT_COLOR_MAP[selectedEvent.type],
                  background: `${EVENT_COLOR_MAP[selectedEvent.type]}15`,
                  borderColor: `${EVENT_COLOR_MAP[selectedEvent.type]}40`,
                }}
              >
                {selectedEvent.type}
              </Tag>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-[var(--tcx-muted)]">Date & Time</span>
              <span className="font-medium text-[var(--tcx-text)]">
                {dayjs(selectedEvent.date).format('dddd, D MMMM YYYY')} at {selectedEvent.startTime} ({selectedEvent.durationMinutes} min)
              </span>
            </div>
            {(() => {
              const rel = selectedEvent.lead ? { type: 'Lead', label: selectedEvent.lead.name, href: `/app/leads/${selectedEvent.lead.id}` } : selectedEvent.deal ? { type: 'Deal', label: `${selectedEvent.deal.dealNumber} · ${selectedEvent.deal.title}`, href: `/app/deals/${selectedEvent.deal.id}` } : selectedEvent.account ? { type: 'Customer', label: selectedEvent.account.name, href: `/app/customers/${selectedEvent.account.id}` } : null;
              if (!rel) return null;
              return (
                <div className="flex items-center justify-between">
                  <span className="text-[var(--tcx-muted)]">Related to</span>
                  <Link href={rel.href} className="font-medium text-[var(--tcx-primary)] hover:underline">
                    {rel.type}: {rel.label}
                  </Link>
                </div>
              );
            })()}
            {selectedEvent.owner && (
              <div className="flex items-center justify-between">
                <span className="text-[var(--tcx-muted)]">Owner</span>
                <span className="font-medium text-[var(--tcx-text)]">{selectedEvent.owner.name}</span>
              </div>
            )}
            {selectedEvent.withWhom && (
              <div className="flex items-center justify-between">
                <span className="text-[var(--tcx-muted)]">With</span>
                <span className="font-medium text-[var(--tcx-text)]">{selectedEvent.withWhom}</span>
              </div>
            )}
            {selectedEvent.description && (
              <div className="pt-2 border-t border-[var(--tcx-border)]">
                <div className="text-xs text-[var(--tcx-muted)] mb-1">Agenda / Details</div>
                <div className="text-[var(--tcx-text)] whitespace-pre-wrap">{selectedEvent.description}</div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
}
