'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useMutation, useQuery } from '@tanstack/react-query';
import { ArrowLeft } from 'lucide-react';
import Link from 'next/link';

import { notificationsApi } from '@/lib/api';
import type { UpdateNotificationRequest } from '@/types/models';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { toast } from 'sonner';

export default function EditNotificationPage() {
  const router = useRouter();
  const params = useParams();
  const notificationId = Number(params.id);

  const [formData, setFormData] = useState<UpdateNotificationRequest>({
    title: '',
    body: '',
    read: false,
  });

  const { data: notification, isLoading } = useQuery({
    queryKey: ['notification', notificationId],
    queryFn: () => notificationsApi.get(notificationId),
    enabled: !!notificationId,
  });

  useEffect(() => {
    if (notification) {
      setFormData({
        title: notification.title,
        body: notification.body,
        read: notification.read,
      });
    }
  }, [notification]);

  const updateMutation = useMutation({
    mutationFn: (data: UpdateNotificationRequest) => notificationsApi.update(notificationId, data),
    onSuccess: () => {
      toast.success('Notification updated successfully');
      router.push(`/notifications/${notificationId}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to update notification');
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.title) {
      toast.error('Please enter a notification title');
      return;
    }
    updateMutation.mutate(formData);
  };

  const updateField = (field: keyof UpdateNotificationRequest, value: unknown) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href={`/notifications/${notificationId}`}>
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Notification</h1>
          <p className="text-muted-foreground">Update notification details for {notification?.username}</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Notification Content</CardTitle>
            <CardDescription>Update the notification message</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="title">Title *</Label>
              <Input
                id="title"
                value={formData.title || ''}
                onChange={(e) => updateField('title', e.target.value)}
                placeholder="Notification title"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="body">Body</Label>
              <Textarea
                id="body"
                value={formData.body || ''}
                onChange={(e) => updateField('body', e.target.value)}
                placeholder="Notification body..."
                rows={4}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Status</CardTitle>
            <CardDescription>Notification read status</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center space-x-2">
              <Switch
                id="read"
                checked={formData.read}
                onCheckedChange={(checked) => updateField('read', checked)}
              />
              <Label htmlFor="read">Marked as Read</Label>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end gap-4">
          <Button type="button" variant="outline" asChild>
            <Link href={`/notifications/${notificationId}`}>Cancel</Link>
          </Button>
          <Button type="submit" disabled={updateMutation.isPending}>
            {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
          </Button>
        </div>
      </form>
    </div>
  );
}
