'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Trash2, ExternalLink, Calendar, DollarSign, User, ClipboardList, Building2, Pencil, Star } from 'lucide-react';
import { toast } from 'sonner';

import { completionsApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

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

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

  const deleteMutation = useMutation({
    mutationFn: () => completionsApi.delete(completionId),
    onSuccess: () => {
      toast.success('Completion deleted successfully');
      queryClient.invalidateQueries({ queryKey: ['completions'] });
      router.push('/completions');
    },
    onError: () => {
      toast.error('Failed to delete completion');
    },
  });

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

  if (error || !completion) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load completion</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/completions">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <h1 className="text-2xl font-bold">Task Completion #{completion.id}</h1>
            <p className="text-muted-foreground">
              Completed on {new Date(completion.completed_at).toLocaleDateString()}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href={`/completions/${completionId}/edit`}>
              <Pencil className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </Button>
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="destructive">
                <Trash2 className="mr-2 h-4 w-4" />
                Delete
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Delete Completion?</AlertDialogTitle>
                <AlertDialogDescription>
                  This will permanently delete this completion record. This action cannot be undone.
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() => deleteMutation.mutate()}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  Delete
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Task Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ClipboardList className="h-5 w-5" />
              Task Information
            </CardTitle>
            <CardDescription>Details about the completed task</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm font-medium text-muted-foreground">Task</div>
              <Link
                href={`/tasks/${completion.task_id}`}
                className="text-lg font-medium text-blue-600 hover:underline"
              >
                {completion.task_title}
              </Link>
            </div>
            <div>
              <div className="text-sm font-medium text-muted-foreground">Residence</div>
              <Link
                href={`/residences/${completion.residence_id}`}
                className="text-blue-600 hover:underline flex items-center gap-1"
              >
                <Building2 className="h-4 w-4" />
                {completion.residence_name}
              </Link>
            </div>
          </CardContent>
        </Card>

        {/* Completion Details */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5" />
              Completion Details
            </CardTitle>
            <CardDescription>When and who completed the task</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm font-medium text-muted-foreground">Completed By</div>
              <Link
                href={`/users/${completion.completed_by_id}`}
                className="text-blue-600 hover:underline flex items-center gap-1"
              >
                <User className="h-4 w-4" />
                {completion.completed_by}
              </Link>
            </div>
            <div>
              <div className="text-sm font-medium text-muted-foreground">Completed At</div>
              <div>{new Date(completion.completed_at).toLocaleString()}</div>
            </div>
            <div>
              <div className="text-sm font-medium text-muted-foreground">Actual Cost</div>
              {completion.actual_cost ? (
                <Badge variant="outline" className="text-base">
                  <DollarSign className="h-4 w-4 mr-1" />
                  {completion.actual_cost}
                </Badge>
              ) : (
                <span className="text-muted-foreground">Not recorded</span>
              )}
            </div>
            <div>
              <div className="text-sm font-medium text-muted-foreground">Rating</div>
              {completion.rating ? (
                <div className="flex items-center gap-1">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <Star
                      key={star}
                      className={`h-5 w-5 ${
                        star <= completion.rating!
                          ? 'fill-yellow-400 text-yellow-400'
                          : 'text-gray-300'
                      }`}
                    />
                  ))}
                  <span className="ml-2 text-sm">({completion.rating}/5)</span>
                </div>
              ) : (
                <span className="text-muted-foreground">Not rated</span>
              )}
            </div>
            <div>
              <div className="text-sm font-medium text-muted-foreground">Record Created</div>
              <div>{new Date(completion.created_at).toLocaleString()}</div>
            </div>
          </CardContent>
        </Card>

        {/* Notes */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>Notes</CardTitle>
            <CardDescription>Additional notes about this completion</CardDescription>
          </CardHeader>
          <CardContent>
            {completion.notes ? (
              <p className="whitespace-pre-wrap">{completion.notes}</p>
            ) : (
              <p className="text-muted-foreground italic">No notes provided</p>
            )}
          </CardContent>
        </Card>

        {/* Photos */}
        {completion.images && completion.images.length > 0 && (
          <Card className="md:col-span-2">
            <CardHeader>
              <CardTitle>Completion Photos ({completion.images.length})</CardTitle>
              <CardDescription>Photo evidence of task completion</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-6 md:grid-cols-2">
                {completion.images.map((image, index) => (
                  <div key={image.id || index} className="space-y-2">
                    <div className="relative">
                      <img
                        src={image.image_url}
                        alt={image.caption || `Completion photo ${index + 1}`}
                        className="rounded-lg border object-contain w-full"
                      />
                    </div>
                    {image.caption && (
                      <p className="text-sm text-muted-foreground text-center">{image.caption}</p>
                    )}
                    <div className="flex justify-center">
                      <a
                        href={image.image_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-1 text-sm text-blue-600 hover:underline"
                      >
                        <ExternalLink className="h-4 w-4" />
                        Open full size
                      </a>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
