'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 { tasksApi, usersApi, residencesApi, lookupsApi, contractorsApi } from '@/lib/api';
import type { UpdateTaskRequest } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { toast } from 'sonner';

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

  const [formData, setFormData] = useState<UpdateTaskRequest>({});

  const { data: task, isLoading: taskLoading } = useQuery({
    queryKey: ['task', taskId],
    queryFn: () => tasksApi.get(taskId),
    enabled: !!taskId,
  });

  const { data: usersData, isLoading: usersLoading } = useQuery({
    queryKey: ['users', { per_page: 1000 }],
    queryFn: () => usersApi.list({ per_page: 1000 }),
  });

  const { data: residencesData, isLoading: residencesLoading } = useQuery({
    queryKey: ['residences', { per_page: 1000 }],
    queryFn: () => residencesApi.list({ per_page: 1000 }),
  });

  const { data: categories, isLoading: categoriesLoading } = useQuery({
    queryKey: ['lookups', 'categories'],
    queryFn: () => lookupsApi.categories.list(),
  });

  const { data: priorities, isLoading: prioritiesLoading } = useQuery({
    queryKey: ['lookups', 'priorities'],
    queryFn: () => lookupsApi.priorities.list(),
  });

  const { data: frequencies, isLoading: frequenciesLoading } = useQuery({
    queryKey: ['lookups', 'frequencies'],
    queryFn: () => lookupsApi.frequencies.list(),
  });

  const { data: contractorsData } = useQuery({
    queryKey: ['contractors', { per_page: 1000 }],
    queryFn: () => contractorsApi.list({ per_page: 1000 }),
  });

  const { data: allTasks } = useQuery({
    queryKey: ['tasks', { per_page: 1000 }],
    queryFn: () => tasksApi.list({ per_page: 1000 }),
  });

  const [formInitialized, setFormInitialized] = useState(false);

  // Wait for ALL data including lookups before initializing form
  const lookupsLoaded = !categoriesLoading && !prioritiesLoading && !frequenciesLoading;

  useEffect(() => {
    if (task && lookupsLoaded && !formInitialized) {
      setFormData({
        residence_id: task.residence_id,
        created_by_id: task.created_by_id,
        assigned_to_id: task.assigned_to_id,
        title: task.title,
        description: task.description,
        category_id: task.category_id,
        priority_id: task.priority_id,
        in_progress: task.in_progress,
        frequency_id: task.frequency_id,
        due_date: task.due_date,
        next_due_date: task.next_due_date,
        estimated_cost: task.estimated_cost,
        actual_cost: task.actual_cost,
        contractor_id: task.contractor_id,
        parent_task_id: task.parent_task_id,
        is_cancelled: task.is_cancelled,
        is_archived: task.is_archived,
      });
      setFormInitialized(true);
    }
  }, [task, lookupsLoaded, formInitialized]);

  const isDataLoading = taskLoading || usersLoading || residencesLoading || !lookupsLoaded || !formInitialized;

  const updateMutation = useMutation({
    mutationFn: (data: UpdateTaskRequest) => tasksApi.update(taskId, data),
    onSuccess: () => {
      toast.success('Task updated successfully');
      router.push(`/tasks/${taskId}`);
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to update task');
    },
  });

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

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

  if (isDataLoading) {
    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={`/tasks/${taskId}`}>
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Task</h1>
          <p className="text-muted-foreground">Update task details</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Assignment</CardTitle>
            <CardDescription>Task ownership and assignment</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="residence_id">Residence *</Label>
                <Select
                  value={formData.residence_id?.toString() || ''}
                  onValueChange={(value) => updateField('residence_id', Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select residence" />
                  </SelectTrigger>
                  <SelectContent>
                    {residencesData?.data?.map((res) => (
                      <SelectItem key={res.id} value={res.id.toString()}>
                        {res.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="created_by_id">Created By *</Label>
                <Select
                  value={formData.created_by_id?.toString() || ''}
                  onValueChange={(value) => updateField('created_by_id', Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select creator" />
                  </SelectTrigger>
                  <SelectContent>
                    {usersData?.data?.map((user) => (
                      <SelectItem key={user.id} value={user.id.toString()}>
                        {user.username} ({user.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="assigned_to_id">Assigned To</Label>
                <Select
                  value={formData.assigned_to_id?.toString() || 'none'}
                  onValueChange={(value) => updateField('assigned_to_id', value === 'none' ? undefined : Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select assignee" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">None</SelectItem>
                    {usersData?.data?.map((user) => (
                      <SelectItem key={user.id} value={user.id.toString()}>
                        {user.username} ({user.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="contractor_id">Contractor</Label>
                <Select
                  value={formData.contractor_id?.toString() || 'none'}
                  onValueChange={(value) => updateField('contractor_id', value === 'none' ? undefined : Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select contractor" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">None</SelectItem>
                    {contractorsData?.data?.map((contractor) => (
                      <SelectItem key={contractor.id} value={contractor.id.toString()}>
                        {contractor.name} {contractor.company && `(${contractor.company})`}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Basic Information</CardTitle>
            <CardDescription>Update the task details</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="Task title"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={formData.description || ''}
                onChange={(e) => updateField('description', e.target.value)}
                placeholder="Task description..."
                rows={3}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Classification</CardTitle>
            <CardDescription>Task category, priority, and status</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="category_id">Category</Label>
                <Select
                  value={formData.category_id?.toString() || 'none'}
                  onValueChange={(value) => updateField('category_id', value === 'none' ? undefined : Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select category" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">None</SelectItem>
                    {categories?.map((cat: { id: number; name: string }) => (
                      <SelectItem key={cat.id} value={cat.id.toString()}>
                        {cat.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="priority_id">Priority</Label>
                <Select
                  value={formData.priority_id?.toString() || 'none'}
                  onValueChange={(value) => updateField('priority_id', value === 'none' ? undefined : Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select priority" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">None</SelectItem>
                    {priorities?.map((pri: { id: number; name: string }) => (
                      <SelectItem key={pri.id} value={pri.id.toString()}>
                        {pri.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="flex items-center space-x-2 pt-8">
                <input
                  type="checkbox"
                  id="in_progress"
                  checked={formData.in_progress ?? false}
                  onChange={(e) => updateField('in_progress', e.target.checked)}
                  className="h-4 w-4 rounded border-gray-300"
                />
                <Label htmlFor="in_progress">In Progress</Label>
              </div>
              <div className="space-y-2">
                <Label htmlFor="frequency_id">Frequency</Label>
                <Select
                  value={formData.frequency_id?.toString() || 'none'}
                  onValueChange={(value) => updateField('frequency_id', value === 'none' ? undefined : Number(value))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select frequency" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">None (One-time)</SelectItem>
                    {frequencies?.map((freq: { id: number; name: string }) => (
                      <SelectItem key={freq.id} value={freq.id.toString()}>
                        {freq.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Scheduling & Cost</CardTitle>
            <CardDescription>Due date and cost information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="due_date">Due Date</Label>
                <Input
                  id="due_date"
                  type="date"
                  value={formData.due_date || ''}
                  onChange={(e) => updateField('due_date', e.target.value || undefined)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="next_due_date">Next Due Date</Label>
                <Input
                  id="next_due_date"
                  type="date"
                  value={formData.next_due_date || ''}
                  onChange={(e) => updateField('next_due_date', e.target.value || undefined)}
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="estimated_cost">Estimated Cost ($)</Label>
                <Input
                  id="estimated_cost"
                  type="number"
                  step="0.01"
                  value={formData.estimated_cost ?? ''}
                  onChange={(e) => updateField('estimated_cost', e.target.value ? Number(e.target.value) : undefined)}
                  placeholder="0.00"
                />
              </div>
              <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 ? Number(e.target.value) : undefined)}
                  placeholder="0.00"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Relationships</CardTitle>
            <CardDescription>Link to parent task (for recurring tasks)</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="parent_task_id">Parent Task</Label>
              <Select
                value={formData.parent_task_id?.toString() || 'none'}
                onValueChange={(value) => updateField('parent_task_id', value === 'none' ? undefined : Number(value))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select parent task" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">None</SelectItem>
                  {allTasks?.data?.filter(t => t.id !== taskId).map((t) => (
                    <SelectItem key={t.id} value={t.id.toString()}>
                      {t.title} (#{t.id})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Status Flags</CardTitle>
            <CardDescription>Task state flags</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-6">
              <div className="flex items-center space-x-2">
                <Switch
                  id="is_cancelled"
                  checked={formData.is_cancelled}
                  onCheckedChange={(checked) => updateField('is_cancelled', checked)}
                />
                <Label htmlFor="is_cancelled">Cancelled</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="is_archived"
                  checked={formData.is_archived}
                  onCheckedChange={(checked) => updateField('is_archived', checked)}
                />
                <Label htmlFor="is_archived">Archived</Label>
              </div>
            </div>
          </CardContent>
        </Card>

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