'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { ArrowLeft, Trash2, FileText, ExternalLink, Pencil, ImageIcon, X } from 'lucide-react';
import { toast } from 'sonner';

import { documentsApi } 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 {
  Dialog,
  DialogContent,
} from '@/components/ui/dialog';

export function DocumentDetailClient() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const documentId = Number(params.id);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  const { data: document, isLoading, error } = useQuery({
    queryKey: ['document', documentId],
    queryFn: () => documentsApi.get(documentId),
    enabled: !!documentId,
  });

  const deleteMutation = useMutation({
    mutationFn: () => documentsApi.delete(documentId),
    onSuccess: () => {
      toast.success('Document deactivated successfully');
      queryClient.invalidateQueries({ queryKey: ['documents'] });
      router.push('/documents');
    },
    onError: () => {
      toast.error('Failed to deactivate document');
    },
  });

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

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

  const isExpired = document.expiry_date && new Date(document.expiry_date) < new Date();

  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="/documents">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <FileText className="h-5 w-5 text-muted-foreground" />
              <h1 className="text-2xl font-bold">{document.title}</h1>
            </div>
            <p className="text-muted-foreground">{document.residence_name}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {document.file_url && (
            <Button variant="outline" asChild>
              <a href={document.file_url} target="_blank" rel="noopener noreferrer">
                <ExternalLink className="mr-2 h-4 w-4" />
                View File
              </a>
            </Button>
          )}
          <Button variant="outline" asChild>
            <Link href={`/documents/${documentId}/edit`}>
              <Pencil className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </Button>
          <Button
            variant="destructive"
            onClick={() => {
              if (confirm('Are you sure you want to deactivate this document?')) {
                deleteMutation.mutate();
              }
            }}
            disabled={deleteMutation.isPending}
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Deactivate
          </Button>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Document Details */}
        <Card>
          <CardHeader>
            <CardTitle>Document Details</CardTitle>
            <CardDescription>Basic document information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm font-medium text-muted-foreground">Description</div>
              <div className="whitespace-pre-wrap">{document.description || '-'}</div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Type</div>
                <Badge variant="outline">{document.document_type}</Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Status</div>
                <Badge variant={document.is_active ? 'default' : 'secondary'}>
                  {document.is_active ? 'Active' : 'Inactive'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">File Name</div>
                <div className="truncate">{document.file_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Vendor</div>
                <div>{document.vendor || '-'}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Dates & Warranty Info */}
        <Card>
          <CardHeader>
            <CardTitle>Dates</CardTitle>
            <CardDescription>Important dates for this document</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Purchase Date</div>
                <div>
                  {document.purchase_date
                    ? new Date(document.purchase_date).toLocaleDateString()
                    : '-'}
                </div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Expiry Date</div>
                <div className={isExpired ? 'text-red-500 font-medium' : ''}>
                  {document.expiry_date
                    ? new Date(document.expiry_date).toLocaleDateString()
                    : '-'}
                  {isExpired && ' (Expired)'}
                </div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Created</div>
                <div>{new Date(document.created_at).toLocaleDateString()}</div>
              </div>
              {document.task_title && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Related Task</div>
                  <div>{document.task_title}</div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Document Images */}
      {document.images && document.images.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ImageIcon className="h-5 w-5" />
              Images ({document.images.length})
            </CardTitle>
            <CardDescription>Photos and images attached to this document</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
              {document.images.map((image) => (
                <div
                  key={image.id}
                  className="relative aspect-square rounded-lg overflow-hidden border cursor-pointer hover:ring-2 hover:ring-primary transition-all"
                  onClick={() => setSelectedImage(image.image_url)}
                >
                  <Image
                    src={image.image_url}
                    alt={image.caption || 'Document image'}
                    fill
                    className="object-cover"
                    sizes="(max-width: 768px) 50vw, (max-width: 1200px) 33vw, 25vw"
                  />
                  {image.caption && (
                    <div className="absolute bottom-0 left-0 right-0 bg-black/60 text-white text-xs p-1 truncate">
                      {image.caption}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Image Modal */}
      <Dialog open={!!selectedImage} onOpenChange={() => setSelectedImage(null)}>
        <DialogContent className="max-w-4xl p-0 overflow-hidden">
          {selectedImage && (
            <div className="relative">
              <Button
                variant="ghost"
                size="icon"
                className="absolute top-2 right-2 z-10 bg-black/50 hover:bg-black/70 text-white"
                onClick={() => setSelectedImage(null)}
              >
                <X className="h-4 w-4" />
              </Button>
              <Image
                src={selectedImage}
                alt="Document image"
                width={1200}
                height={800}
                className="w-full h-auto max-h-[80vh] object-contain"
              />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
