'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface ReminderPrefs {
  delivery: 'immediate' | 'daily' | 'weekly' | 'off';
  digestTime?: string;
  digestDayOfWeek?: number;
  timezone?: string;
}

interface UserPrefsResponse {
  reminders?: ReminderPrefs;
  timezone?: string;
  portReminderDigestEnabled?: boolean;
}

const DAYS = [
  { value: '0', label: 'Sunday' },
  { value: '1', label: 'Monday' },
  { value: '2', label: 'Tuesday' },
  { value: '3', label: 'Wednesday' },
  { value: '4', label: 'Thursday' },
  { value: '5', label: 'Friday' },
  { value: '6', label: 'Saturday' },
];

export function ReminderDigestForm() {
  const qc = useQueryClient();
  const { data, isLoading } = useQuery<UserPrefsResponse>({
    queryKey: ['user', 'preferences'],
    queryFn: () =>
      apiFetch<{ data: UserPrefsResponse }>('/api/v1/users/me/preferences').then((r) => r.data),
  });
  // Key-based remount: the body is keyed on the loaded payload signature
  // so the useState initializers re-run when the server data first lands
  // or genuinely changes. Replaces the prior useEffect(setState) sync.
  if (isLoading || !data) {
    return <ReminderDigestFormBody key="loading" data={data} isLoading={isLoading} qc={qc} />;
  }
  const r = data.reminders ?? null;
  const signature = `${r?.delivery ?? ''}|${r?.digestTime ?? ''}|${r?.digestDayOfWeek ?? ''}|${r?.timezone ?? data.timezone ?? ''}`;
  return <ReminderDigestFormBody key={signature} data={data} isLoading={false} qc={qc} />;
}

function ReminderDigestFormBody({
  data,
  isLoading,
  qc,
}: {
  data: UserPrefsResponse | undefined;
  isLoading: boolean;
  qc: ReturnType<typeof useQueryClient>;
}) {
  const r = data?.reminders;
  const [delivery, setDelivery] = useState<ReminderPrefs['delivery']>(r?.delivery ?? 'immediate');
  const [digestTime, setDigestTime] = useState(r?.digestTime ?? '09:00');
  const [digestDay, setDigestDay] = useState(String(r?.digestDayOfWeek ?? 1));
  const [timezone, setTimezone] = useState(r?.timezone ?? data?.timezone ?? 'Europe/Warsaw');

  const mutation = useMutation({
    mutationFn: () =>
      apiFetch('/api/v1/users/me/preferences', {
        method: 'PATCH',
        body: {
          reminders: {
            delivery,
            ...(delivery !== 'immediate' && delivery !== 'off' ? { digestTime, timezone } : {}),
            ...(delivery === 'weekly' ? { digestDayOfWeek: Number(digestDay) } : {}),
          },
        },
      }),
    onSuccess: () => {
      toast.success('Reminder preferences saved');
      qc.invalidateQueries({ queryKey: ['user', 'preferences'] });
    },
    onError: (err) => toastError(err),
  });

  if (isLoading) {
    return (
      <Card>
        <CardContent className="py-6 text-sm text-muted-foreground">
          <Loader2 className="mr-2 inline h-4 w-4 animate-spin" />
          Loading…
        </CardContent>
      </Card>
    );
  }

  if (!data?.portReminderDigestEnabled) {
    return null;
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Reminder digest</CardTitle>
        <CardDescription>
          Choose how reminder notifications are delivered to you. Immediate fires as soon as a
          reminder triggers; daily/weekly batch them into a digest at the time you pick.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-1">
          <Label>Delivery</Label>
          <Select
            value={delivery}
            onValueChange={(v) => setDelivery(v as ReminderPrefs['delivery'])}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="immediate">Immediate (default)</SelectItem>
              <SelectItem value="daily">Daily digest</SelectItem>
              <SelectItem value="weekly">Weekly digest</SelectItem>
              <SelectItem value="off">Off (do not send)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {(delivery === 'daily' || delivery === 'weekly') && (
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label>Delivery time (HH:MM)</Label>
              <Input
                value={digestTime}
                onChange={(e) => setDigestTime(e.target.value)}
                placeholder="09:00"
              />
            </div>
            {delivery === 'weekly' && (
              <div className="space-y-1">
                <Label>Day of week</Label>
                <Select value={digestDay} onValueChange={setDigestDay}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {DAYS.map((d) => (
                      <SelectItem key={d.value} value={d.value}>
                        {d.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            <div className="space-y-1 col-span-2">
              <Label>Timezone (IANA)</Label>
              <Input
                value={timezone}
                onChange={(e) => setTimezone(e.target.value)}
                placeholder="Europe/Warsaw"
              />
            </div>
          </div>
        )}

        <div className="flex justify-end">
          <Button onClick={() => mutation.mutate()} disabled={mutation.isPending}>
            {mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Save digest preferences
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
