'use client';

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

import { contractorsApi } 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';

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

  const { data: contractor, isLoading, error } = useQuery({
    queryKey: ['contractor', contractorId],
    queryFn: () => contractorsApi.get(contractorId),
    enabled: !!contractorId,
  });

  const deleteMutation = useMutation({
    mutationFn: () => contractorsApi.delete(contractorId),
    onSuccess: () => {
      toast.success('Contractor deactivated successfully');
      queryClient.invalidateQueries({ queryKey: ['contractors'] });
      router.push('/contractors');
    },
    onError: () => {
      toast.error('Failed to deactivate contractor');
    },
  });

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

  if (error || !contractor) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load contractor</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="/contractors">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-2xl font-bold">{contractor.name}</h1>
              {contractor.is_favorite && (
                <Star className="h-5 w-5 fill-yellow-400 text-yellow-400" />
              )}
            </div>
            <p className="text-muted-foreground">{contractor.company || contractor.residence_name}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href={`/contractors/${contractorId}/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 contractor?')) {
                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">
        {/* Contact Info */}
        <Card>
          <CardHeader>
            <CardTitle>Contact Information</CardTitle>
            <CardDescription>Ways to reach this contractor</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-3">
              {contractor.phone && (
                <div className="flex items-center gap-2">
                  <Phone className="h-4 w-4 text-muted-foreground" />
                  <span>{contractor.phone}</span>
                </div>
              )}
              {contractor.email && (
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4 text-muted-foreground" />
                  <a href={`mailto:${contractor.email}`} className="text-blue-600 hover:underline">
                    {contractor.email}
                  </a>
                </div>
              )}
              {contractor.website && (
                <div className="flex items-center gap-2">
                  <Globe className="h-4 w-4 text-muted-foreground" />
                  <a
                    href={contractor.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:underline"
                  >
                    {contractor.website}
                  </a>
                </div>
              )}
              {contractor.city && (
                <div className="text-muted-foreground">{contractor.city}</div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Status & Details */}
        <Card>
          <CardHeader>
            <CardTitle>Status & Details</CardTitle>
            <CardDescription>Contractor status and statistics</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={contractor.is_active ? 'default' : 'secondary'}>
                  {contractor.is_active ? 'Yes' : 'No'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Favorite</div>
                <Badge variant={contractor.is_favorite ? 'default' : 'outline'}>
                  {contractor.is_favorite ? 'Yes' : 'No'}
                </Badge>
              </div>
            </div>

            <Separator />

            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Rating</div>
                <div className="text-2xl font-bold">
                  {contractor.rating?.toFixed(1) ?? '-'}
                </div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Tasks</div>
                <div className="text-2xl font-bold">{contractor.task_count}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Specialties */}
        {contractor.specialties && contractor.specialties.length > 0 && (
          <Card className="md:col-span-2">
            <CardHeader>
              <CardTitle>Specialties</CardTitle>
              <CardDescription>Areas of expertise</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-2">
                {contractor.specialties.map((specialty) => (
                  <Badge key={specialty} variant="outline">
                    {specialty}
                  </Badge>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
