import { useState, type FormEvent, type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { CheckSquare, Plus, Trash2, Pencil } from 'lucide-react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  createReminder,
  deleteReminder,
  fetchReminders,
  fetchReminderStats,
  updateReminder,
  type Reminder,
  type ReminderInput,
  type ReminderStats,
} from '@/api/reminders';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';

const Root = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
`;

const PageHeading = styled.h1`
  margin: 0;
  padding: 14px 20px;
  font-size: 18px;
  font-weight: 700;
  color: #e0e0f0;
  border-bottom: 1px solid #2a2a38;
  background: #0a0a0f;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
`;

const Stats = styled.span`
  font-size: 11px;
  color: #8a8a9a;
  font-weight: 500;
`;

const Toolbar = styled.div`
  display: flex;
  gap: 8px;
  padding: 10px 20px;
  border-bottom: 1px solid #1e1e2a;
  background: #0d0d14;
`;

const PrimaryButton = styled.button`
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 600;
  color: #0a0a0f;
  background: #c9a84c;
  border: 1px solid #c9a84c;
  border-radius: 5px;
  cursor: pointer;

  &:hover { background: #d4b455; }
  &:disabled { opacity: 0.5; cursor: not-allowed; }
`;

const SecondaryButton = styled.button`
  padding: 6px 12px;
  font-size: 12px;
  color: #b0b0c0;
  background: transparent;
  border: 1px solid #2a2a38;
  border-radius: 5px;
  cursor: pointer;
  &:hover { color: #e0e0f0; border-color: #4a4a58; }
`;

const IconButton = styled.button`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  color: #8a8a9a;

  &:hover { color: #e0e0f0; border-color: #2a2a38; background: #13131a; }
`;

const FormCard = styled.form`
  margin: 12px 20px;
  padding: 14px;
  background: #13131a;
  border: 1px solid #2a2a38;
  border-radius: 6px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
`;

const Field = styled.label`
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 11px;
  color: #8a8a9a;
`;

const FieldFull = styled(Field)`
  grid-column: 1 / -1;
`;

const Input = styled.input`
  padding: 6px 8px;
  font-size: 12px;
  color: #e0e0f0;
  background: #0a0a0f;
  border: 1px solid #2a2a38;
  border-radius: 4px;
  outline: none;
  &:focus { border-color: #c9a84c; }
`;

const TextArea = styled.textarea`
  padding: 6px 8px;
  font-size: 12px;
  color: #e0e0f0;
  background: #0a0a0f;
  border: 1px solid #2a2a38;
  border-radius: 4px;
  outline: none;
  min-height: 60px;
  resize: vertical;
  font-family: inherit;
  &:focus { border-color: #c9a84c; }
`;

const FormActions = styled.div`
  grid-column: 1 / -1;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
`;

const List = styled.ul`
  list-style: none;
  margin: 0;
  padding: 0;
  overflow-y: auto;
  flex: 1;
`;

const Row = styled.li<{ $completed: boolean }>`
  padding: 12px 20px;
  border-bottom: 1px solid #1e1e2a;
  display: flex;
  align-items: center;
  gap: 12px;
  opacity: ${({ $completed }) => ($completed ? 0.55 : 1)};

  &:hover { background: #13131a; }
`;

const RowMain = styled.div`
  flex: 1;
  min-width: 0;
`;

const RowTitle = styled.div<{ $completed: boolean }>`
  font-size: 13px;
  font-weight: 600;
  color: #e0e0f0;
  display: flex;
  align-items: center;
  gap: 8px;
  text-decoration: ${({ $completed }) => ($completed ? 'line-through' : 'none')};
`;

const RowMeta = styled.div`
  font-size: 11px;
  color: #8a8a9a;
  margin-top: 2px;
`;

const RowActions = styled.div`
  display: flex;
  gap: 4px;
`;

const PendingBadge = styled.span`
  font-size: 9px;
  font-weight: 700;
  letter-spacing: 0.04em;
  color: #c9a84c;
  background: rgba(201,168,76,0.12);
  border: 1px solid rgba(201,168,76,0.3);
  border-radius: 3px;
  padding: 1px 5px;
  text-transform: uppercase;
`;

const SpinnerWrap = styled.div`
  padding: 20px;
  font-size: 12px;
  color: #8a8a9a;
  text-align: center;
`;

const Checkbox = styled.input`
  width: 16px;
  height: 16px;
  accent-color: #c9a84c;
  cursor: pointer;
`;

const DEVICE_ID: string | undefined = undefined;

interface FormState {
  calendarIdentifier: string;
  title: string;
  notes: string;
  dueDate: string;
  priority: number;
}

function blankForm(defaultCalendar: string): FormState {
  return {
    calendarIdentifier: defaultCalendar,
    title: '',
    notes: '',
    dueDate: '',
    priority: 0,
  };
}

function formFromReminder(r: Reminder): FormState {
  return {
    calendarIdentifier: r.calendarIdentifier,
    title: r.title,
    notes: r.notes ?? '',
    dueDate: r.dueDate ? toLocalInput(r.dueDate) : '',
    priority: r.priority,
  };
}

function toLocalInput(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return '';
  const pad = (n: number): string => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function formToInput(form: FormState): ReminderInput {
  const input: ReminderInput = {
    calendarIdentifier: form.calendarIdentifier,
    title: form.title,
    priority: form.priority,
    ...(form.notes ? { notes: form.notes } : {}),
    ...(form.dueDate ? { dueDate: new Date(form.dueDate).toISOString() } : {}),
  };
  return input;
}

export function RemindersTab(): ReactElement {
  const qc = useQueryClient();
  const [editing, setEditing] = useState<Reminder | null>(null);
  const [creating, setCreating] = useState(false);
  const [pendingIds, setPendingIds] = useState<ReadonlySet<string>>(new Set());

  const statsQ = useQuery<ReminderStats>({
    queryKey: ['reminder-stats'],
    queryFn: fetchReminderStats,
    refetchInterval: 30_000,
  });
  const listQ = useQuery<Reminder[]>({
    queryKey: ['reminders', DEVICE_ID],
    queryFn: () => fetchReminders({ limit: 50 }),
    refetchInterval: 30_000,
  });

  const reminders = listQ.data ?? [];
  const firstCalendarId = reminders[0]?.calendarIdentifier ?? '';

  const [form, setForm] = useState<FormState>(() => blankForm(''));

  const markPending = (id: string): void => {
    setPendingIds((prev) => {
      const next = new Set(prev);
      next.add(id);
      return next;
    });
  };

  const startCreate = (): void => {
    setEditing(null);
    setForm(blankForm(firstCalendarId));
    setCreating(true);
  };
  const startEdit = (r: Reminder): void => {
    setCreating(false);
    setEditing(r);
    setForm(formFromReminder(r));
  };
  const cancel = (): void => {
    setEditing(null);
    setCreating(false);
  };

  const createMut = useMutation({
    mutationFn: (input: ReminderInput) => createReminder(input, DEVICE_ID ?? ''),
    onSuccess: (res) => {
      markPending(res.sendQueueId);
      qc.invalidateQueries({ queryKey: ['reminders'] });
      qc.invalidateQueries({ queryKey: ['reminder-stats'] });
      cancel();
    },
  });

  const updateMut = useMutation({
    mutationFn: (vars: { id: string; patch: Partial<ReminderInput> }) =>
      updateReminder(vars.id, vars.patch, DEVICE_ID ?? ''),
    onSuccess: (_, vars) => {
      markPending(vars.id);
      qc.invalidateQueries({ queryKey: ['reminders'] });
    },
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => deleteReminder(id, DEVICE_ID ?? ''),
    onSuccess: (_, id) => {
      markPending(id);
      qc.invalidateQueries({ queryKey: ['reminders'] });
      qc.invalidateQueries({ queryKey: ['reminder-stats'] });
    },
  });

  const onSubmit = (e: FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    if (!form.title) return;
    const input = formToInput(form);
    if (editing) {
      updateMut.mutate({ id: editing.reminderIdentifier, patch: input });
      cancel();
    } else {
      createMut.mutate(input);
    }
  };

  const toggleComplete = (r: Reminder): void => {
    updateMut.mutate({
      id: r.reminderIdentifier,
      patch: { isCompleted: !r.isCompleted },
    });
  };

  const onDelete = (r: Reminder): void => {
    if (window.confirm(`Delete "${r.title}"?`)) {
      deleteMut.mutate(r.reminderIdentifier);
    }
  };

  const showForm = creating || editing !== null;
  const stats = statsQ.data;
  const statsLine = stats
    ? `${stats.totalReminders} reminder${stats.totalReminders !== 1 ? 's' : ''} · ${stats.totalLists} list${stats.totalLists !== 1 ? 's' : ''}${stats.lastSyncAt ? ` · synced ${new Date(stats.lastSyncAt).toLocaleTimeString()}` : ''}`
    : '';

  return (
    <Root>
      <PageHeading>
        <span>Reminders</span>
        <Stats>{statsLine}</Stats>
      </PageHeading>
      <Toolbar>
        <PrimaryButton type="button" onClick={startCreate}>
          <Plus size={13} /> Add reminder
        </PrimaryButton>
      </Toolbar>

      {showForm && (
        <FormCard onSubmit={onSubmit}>
          <Field>
            <span>List identifier</span>
            <Input
              type="text"
              value={form.calendarIdentifier}
              onChange={(e) => setForm({ ...form, calendarIdentifier: e.target.value })}
              required
              placeholder="e.g. default list id"
            />
          </Field>
          <Field>
            <span>Title</span>
            <Input
              type="text"
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              required
            />
          </Field>
          <Field>
            <span>Due date</span>
            <Input
              type="datetime-local"
              value={form.dueDate}
              onChange={(e) => setForm({ ...form, dueDate: e.target.value })}
            />
          </Field>
          <Field>
            <span>Priority (0–9)</span>
            <Input
              type="number"
              min={0}
              max={9}
              value={form.priority}
              onChange={(e) => setForm({ ...form, priority: Number(e.target.value) })}
            />
          </Field>
          <FieldFull>
            <span>Notes</span>
            <TextArea
              value={form.notes}
              onChange={(e) => setForm({ ...form, notes: e.target.value })}
            />
          </FieldFull>
          <FormActions>
            <SecondaryButton type="button" onClick={cancel}>Cancel</SecondaryButton>
            <PrimaryButton type="submit" disabled={createMut.isPending || updateMut.isPending}>
              {editing ? 'Save changes' : 'Create reminder'}
            </PrimaryButton>
          </FormActions>
        </FormCard>
      )}

      {listQ.isLoading && <SpinnerWrap aria-live="polite">Loading reminders…</SpinnerWrap>}
      {listQ.error && <PageError message="Failed to load reminders" />}
      {!listQ.isLoading && !listQ.error && reminders.length === 0 && !showForm && (
        <EmptyState
          icon={<CheckSquare size={36} />}
          heading="No reminders yet"
          sub="Click Add to create one."
        />
      )}
      {!listQ.isLoading && reminders.length > 0 && (
        <List aria-label="Reminders">
          {reminders.map((r) => {
            const isPending =
              pendingIds.has(r.reminderIdentifier) ||
              (deleteMut.isPending && deleteMut.variables === r.reminderIdentifier);
            return (
              <Row key={r.reminderIdentifier} $completed={r.isCompleted}>
                <Checkbox
                  type="checkbox"
                  checked={r.isCompleted}
                  onChange={() => toggleComplete(r)}
                  aria-label={r.isCompleted ? 'Mark incomplete' : 'Mark complete'}
                />
                <RowMain>
                  <RowTitle $completed={r.isCompleted}>
                    {r.title}
                    {isPending && <PendingBadge>Pending sync</PendingBadge>}
                  </RowTitle>
                  {(r.dueDate || r.notes) && (
                    <RowMeta>
                      {r.dueDate ? `Due ${new Date(r.dueDate).toLocaleString()}` : ''}
                      {r.dueDate && r.notes ? ' · ' : ''}
                      {r.notes ?? ''}
                    </RowMeta>
                  )}
                </RowMain>
                <RowActions>
                  <IconButton type="button" aria-label="Edit" onClick={() => startEdit(r)}>
                    <Pencil size={14} />
                  </IconButton>
                  <IconButton type="button" aria-label="Delete" onClick={() => onDelete(r)}>
                    <Trash2 size={14} />
                  </IconButton>
                </RowActions>
              </Row>
            );
          })}
        </List>
      )}
    </Root>
  );
}
