'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 { completionsApi } from '@/lib/api';
import type { UpdateCompletionRequest } 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 {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { toast } from 'sonner';

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

  const [formData, setFormData] = useState<UpdateCompletionRequest>({
    notes: '',
    actual_cost: '',
  });

  const { data: completion, isLoading } = useQuery({
    queryKey: ['completion', completionId],
    queryFn: () => completionsApi.get(completionId),
    enabled: !!completionId,
  });

  useEffect(() => {
    if (completion) {
      setFormData({
        notes: completion.notes || '',
        actual_cost: completion.actual_cost || '',
      });
    }
  }, [completion]);

  const updateMutation = useMutation({
    mutationFn: (data: UpdateCompletionRequest) => completionsApi.update(completionId, data),
    onSuccess: () => {
      toast.success('Completion updated successfully');
      router.push(`/completions/${completionId}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to update completion');
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    updateMutation.mutate(formData);
  };

  const updateField = (field: keyof UpdateCompletionRequest, value: string) => {
    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={`/completions/${completionId}`}>
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Completion</h1>
          <p className="text-muted-foreground">Update completion details for {completion?.task_title}</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Completion Details</CardTitle>
            <CardDescription>Update the completion information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="actual_cost">Actual Cost</Label>
              <Input
                id="actual_cost"
                type="number"
                step="0.01"
                value={formData.actual_cost || ''}
                onChange={(e) => updateField('actual_cost', e.target.value)}
                placeholder="0.00"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                value={formData.notes || ''}
                onChange={(e) => updateField('notes', e.target.value)}
                placeholder="Completion notes..."
                rows={4}
              />
            </div>
          </CardContent>
        </Card>

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