'use client';

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

import { residencesApi, tasksApi } 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 { Separator } from '@/components/ui/separator';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

export function ResidenceDetailClient() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const residenceId = Number(params.id);

  const { data: residence, isLoading, error } = useQuery({
    queryKey: ['residence', residenceId],
    queryFn: () => residencesApi.get(residenceId),
    enabled: !!residenceId,
  });

  const { data: tasksData, isLoading: isLoadingTasks } = useQuery({
    queryKey: ['residence-tasks', residenceId],
    queryFn: () => tasksApi.list({ residence_id: residenceId, per_page: 100 }),
    enabled: !!residenceId,
  });

  const deleteMutation = useMutation({
    mutationFn: () => residencesApi.delete(residenceId),
    onSuccess: () => {
      toast.success('Residence deactivated successfully');
      queryClient.invalidateQueries({ queryKey: ['residences'] });
      router.push('/residences');
    },
    onError: () => {
      toast.error('Failed to deactivate residence');
    },
  });

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

  if (error || !residence) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load residence</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="/residences">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{residence.name}</h1>
            <p className="text-muted-foreground">
              {residence.city}, {residence.state_province}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href={`/residences/${residenceId}/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 residence?')) {
                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">
        {/* Property Info */}
        <Card>
          <CardHeader>
            <CardTitle>Property Information</CardTitle>
            <CardDescription>Basic property details</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">Type</div>
                <div>{residence.property_type || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Bedrooms</div>
                <div>{residence.bedrooms ?? '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Bathrooms</div>
                <div>{residence.bathrooms ?? '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Sq Ft</div>
                <div>{residence.square_footage?.toLocaleString() ?? '-'}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Address */}
        <Card>
          <CardHeader>
            <CardTitle>Address</CardTitle>
            <CardDescription>Property location</CardDescription>
          </CardHeader>
          <CardContent className="space-y-2">
            <div>{residence.street_address || '-'}</div>
            <div>
              {residence.city}, {residence.state_province} {residence.postal_code}
            </div>
            <div>{residence.country}</div>
          </CardContent>
        </Card>

        {/* Status */}
        <Card>
          <CardHeader>
            <CardTitle>Status</CardTitle>
            <CardDescription>Property status and flags</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">Active</div>
                <Badge variant={residence.is_active ? 'default' : 'secondary'}>
                  {residence.is_active ? 'Yes' : 'No'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Primary</div>
                <Badge variant={residence.is_primary ? 'default' : 'outline'}>
                  {residence.is_primary ? 'Yes' : 'No'}
                </Badge>
              </div>
            </div>

            <Separator />

            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Tasks</div>
                <div className="text-2xl font-bold">{residence.task_count}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Documents</div>
                <div className="text-2xl font-bold">{residence.document_count}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Owner & Users */}
        <Card>
          <CardHeader>
            <CardTitle>Owner & Users</CardTitle>
            <CardDescription>People with access to this property</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {residence.owner && (
              <div>
                <div className="text-sm font-medium text-muted-foreground">Owner</div>
                <Link
                  href={`/users/${residence.owner.id}`}
                  className="text-blue-600 hover:underline"
                >
                  {residence.owner.username} ({residence.owner.email})
                </Link>
              </div>
            )}

            {residence.shared_users && residence.shared_users.length > 0 && (
              <div>
                <div className="text-sm font-medium text-muted-foreground mb-2">Shared Users</div>
                <div className="space-y-1">
                  {residence.shared_users.map((user) => (
                    <div key={user.id}>
                      <Link
                        href={`/users/${user.id}`}
                        className="text-blue-600 hover:underline"
                      >
                        {user.username}
                      </Link>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Tasks */}
      <Card>
        <CardHeader>
          <CardTitle>Tasks</CardTitle>
          <CardDescription>All tasks for this property</CardDescription>
        </CardHeader>
        <CardContent>
          {isLoadingTasks ? (
            <div className="text-muted-foreground">Loading tasks...</div>
          ) : !tasksData?.data || tasksData.data.length === 0 ? (
            <div className="text-muted-foreground">No tasks for this property</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Title</TableHead>
                  <TableHead>In Progress</TableHead>
                  <TableHead>Priority</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Due Date</TableHead>
                  <TableHead>Created By</TableHead>
                  <TableHead className="w-[50px]"></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {tasksData.data.map((task) => (
                  <TableRow key={task.id}>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-2">
                        {task.title}
                        {task.is_cancelled && (
                          <Badge variant="destructive" className="text-xs">Cancelled</Badge>
                        )}
                        {task.is_archived && (
                          <Badge variant="secondary" className="text-xs">Archived</Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      {task.in_progress ? '✓' : '—'}
                    </TableCell>
                    <TableCell>{task.priority_name || '-'}</TableCell>
                    <TableCell>{task.category_name || '-'}</TableCell>
                    <TableCell>
                      {task.due_date
                        ? new Date(task.due_date).toLocaleDateString()
                        : '-'}
                    </TableCell>
                    <TableCell>{task.created_by_name}</TableCell>
                    <TableCell>
                      <Button variant="ghost" size="icon" asChild>
                        <Link href={`/tasks/${task.id}`}>
                          <ExternalLink className="h-4 w-4" />
                        </Link>
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
