'use client';

import { useState, useEffect } from 'react';
import { useApi } from '@/lib/useApi';
import { listRegimens } from '@/services/regimens';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import { Card, CardHeader } from '@/components/ui/Card';
import { Icon } from '@/components/ui/Icon';
import { PageSkeleton, NoHousehold } from '../helpers';
import Link from 'next/link';
import type { z } from 'zod/v4';
import type { RegimenResponseSchema } from '@meshitrack/shared';

type Regimen = z.infer<typeof RegimenResponseSchema>;
type Medication = Regimen['medications'][number];

const TIME_SLOTS = [
  { key: 'morning', label: 'Morning', icon: 'sun' as const },
  { key: 'afternoon', label: 'Afternoon', icon: 'sun' as const },
  { key: 'evening', label: 'Evening', icon: 'moon' as const },
  { key: 'bedtime', label: 'Bedtime', icon: 'moon' as const },
  { key: 'any', label: 'Any time', icon: 'clock' as const },
] as const;

const FREQUENCY_LABELS: Record<string, string> = {
  daily: 'Once daily',
  twice_daily: 'Twice daily',
  three_times_daily: 'Three times daily',
  weekly: 'Weekly',
  every_other_day: 'Every other day',
  as_needed: 'As needed',
  custom: 'Custom',
};

type SlotEntry = { regimen: Regimen; medication: Medication };

function groupByTimeSlot(regimens: Regimen[]): Record<string, SlotEntry[]> {
  const groups: Record<string, SlotEntry[]> = {
    morning: [],
    afternoon: [],
    evening: [],
    bedtime: [],
    any: [],
  };
  for (const regimen of regimens) {
    for (const medication of regimen.medications) {
      const slot = medication.timeOfDay ?? 'any';
      if (slot in groups) {
        groups[slot].push({ regimen, medication });
      } else {
        groups.any.push({ regimen, medication });
      }
    }
  }
  return groups;
}

function MedicationCard({ regimen, medication }: SlotEntry) {
  const freqLabel =
    medication.frequency === 'custom' && medication.customFrequencyPerDay
      ? `${medication.customFrequencyPerDay}x daily`
      : (FREQUENCY_LABELS[medication.frequency] ?? medication.frequency);

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'flex-start',
        gap: 12,
        padding: '12px 16px',
        borderBottom: '1px solid var(--border)',
      }}
    >
      <div
        style={{
          width: 36,
          height: 36,
          borderRadius: 'var(--r-sm)',
          background: 'var(--brand-soft)',
          display: 'grid',
          placeItems: 'center',
          color: 'var(--brand)',
          flexShrink: 0,
        }}
      >
        <Icon name="pill" size={18} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink-strong)' }}>
          {medication.medicineName}{' '}
          <span style={{ fontWeight: 400, color: 'var(--ink-muted)' }}>
            {medication.medicineStrength} {medication.medicineStrengthUnit}
          </span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-muted)', marginTop: 2 }}>
          {medication.dosage} {medication.dosageUnit} &mdash; {freqLabel}
        </div>
        {medication.instructions && (
          <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 2 }}>
            {medication.instructions}
          </div>
        )}
        <div style={{ fontSize: 11, color: 'var(--ink-faint)', marginTop: 4 }}>
          <span className="mt-pill mt-pill--ghost">{regimen.name}</span>
        </div>
      </div>
    </div>
  );
}

function TimeSlotCard({
  label,
  icon,
  entries,
}: {
  slotKey: string;
  label: string;
  icon: 'sun' | 'moon' | 'clock';
  entries: SlotEntry[];
}) {
  if (entries.length === 0) return null;
  return (
    <Card style={{ marginBottom: 16 }}>
      <CardHeader
        title={label}
        subtitle={`${entries.length} dose${entries.length !== 1 ? 's' : ''}`}
        action={
          <div
            style={{
              width: 32,
              height: 32,
              borderRadius: 'var(--r-sm)',
              background: 'var(--bg-inset)',
              display: 'grid',
              placeItems: 'center',
              color: 'var(--ink-muted)',
            }}
          >
            <Icon name={icon} size={16} />
          </div>
        }
      />
      <div>
        {entries.map(({ regimen, medication }, i) => (
          <MedicationCard
            key={`${regimen._id}-${medication.medicineId}-${i}`}
            regimen={regimen}
            medication={medication}
          />
        ))}
      </div>
    </Card>
  );
}

function ScheduleContent({ householdId }: { householdId: string }) {
  const [regimens, setRegimens] = useState<Regimen[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        setLoading(true);
        const allRegimens: Regimen[] = [];
        let cursor: string | null = null;
        do {
          const res = await listRegimens(householdId, {
            isActive: true,
            limit: 100,
            ...(cursor ? { cursor } : {}),
          });
          allRegimens.push(...res.data);
          cursor = res.pagination.cursor;
        } while (cursor);
        if (!cancelled) setRegimens(allRegimens);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : 'Failed to load regimens');
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    void load();
    return () => {
      cancelled = true;
    };
  }, [householdId]);

  if (loading) return <PageSkeleton />;

  if (error) {
    return <div className="mt-alert mt-alert--danger mb-4">{error}</div>;
  }

  if (regimens.length === 0) {
    return (
      <Card>
        <div
          style={{
            padding: '48px 24px',
            textAlign: 'center',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 12,
          }}
        >
          <div
            style={{
              width: 48,
              height: 48,
              borderRadius: 'var(--r-md)',
              background: 'var(--bg-inset)',
              display: 'grid',
              placeItems: 'center',
              color: 'var(--ink-faint)',
            }}
          >
            <Icon name="clock" size={24} />
          </div>
          <div style={{ fontSize: 15, color: 'var(--ink-muted)' }}>No active regimens found.</div>
          <div style={{ fontSize: 13, color: 'var(--ink-faint)' }}>
            <Link href="/medicines/regimens" className="mt-link">
              Set up a regimen
            </Link>{' '}
            to start tracking your daily schedule.
          </div>
        </div>
      </Card>
    );
  }

  const groups = groupByTimeSlot(regimens);
  const totalDoses = Object.values(groups).reduce((sum, g) => sum + g.length, 0);

  return (
    <>
      <div style={{ marginBottom: 16, fontSize: 13, color: 'var(--ink-muted)' }}>
        {regimens.length} active regimen{regimens.length !== 1 ? 's' : ''} &mdash; {totalDoses} dose
        {totalDoses !== 1 ? 's' : ''} per day
      </div>
      {TIME_SLOTS.map(({ key, label, icon }) => (
        <TimeSlotCard
          key={key}
          slotKey={key}
          label={label}
          icon={icon}
          entries={groups[key] ?? []}
        />
      ))}
    </>
  );
}

export default function SchedulePage() {
  const { householdId, isLoading: sessionLoading } = useApi();

  if (sessionLoading) {
    return (
      <>
        <SetPageHeader
          title="Schedule & Log"
          subtitle="Today and this week"
          crumbs={['Medicines', 'Schedule']}
        />
        <PageSkeleton />
      </>
    );
  }

  if (!householdId) {
    return (
      <>
        <SetPageHeader
          title="Schedule & Log"
          subtitle="Today and this week"
          crumbs={['Medicines', 'Schedule']}
        />
        <NoHousehold />
      </>
    );
  }

  return (
    <>
      <SetPageHeader
        title="Schedule & Log"
        subtitle="Today and this week"
        crumbs={['Medicines', 'Schedule']}
      />
      <div style={{ padding: '28px 32px 56px', maxWidth: 900 }}>
        <ScheduleContent householdId={householdId} />
      </div>
    </>
  );
}
