'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Sparkles, Loader2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { apiFetch } from '@/lib/api/client';

interface Recommendation {
  id: string;
  berthId: string;
  matchScore: string | null;
  matchReasons: Record<string, number> | null;
  source: string;
  mooringNumber: string;
  area: string | null;
  status: string;
  lengthFt: string | null;
  widthFt: string | null;
  draftFt: string | null;
}

interface RecommendationListProps {
  interestId: string;
}

export function RecommendationList({ interestId }: RecommendationListProps) {
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<{ data: Recommendation[] }>({
    queryKey: ['interest-recommendations', interestId],
    queryFn: () => apiFetch(`/api/v1/interests/${interestId}/recommendations`),
  });

  const generateMutation = useMutation({
    mutationFn: () =>
      apiFetch(`/api/v1/interests/${interestId}/recommendations/generate`, {
        method: 'POST',
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['interest-recommendations', interestId] });
    },
  });

  const recommendations = data?.data ?? [];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted-foreground">
          AI-scored berth recommendations based on yacht dimensions.
        </p>
        <Button
          size="sm"
          variant="outline"
          onClick={() => generateMutation.mutate()}
          disabled={generateMutation.isPending}
        >
          {generateMutation.isPending ? (
            <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
          ) : (
            <Sparkles className="mr-1.5 h-4 w-4" />
          )}
          Generate Recommendations
        </Button>
      </div>

      {isLoading ? (
        <div className="space-y-2">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="h-16 bg-muted rounded animate-pulse" />
          ))}
        </div>
      ) : recommendations.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground">
          <p>No recommendations yet. Click &quot;Generate Recommendations&quot; to get started.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {recommendations.map((rec) => {
            const score = rec.matchScore ? Math.round(parseFloat(rec.matchScore)) : 0;
            return (
              <div
                key={rec.id}
                className="border rounded-lg p-3 flex items-center gap-4"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-sm font-medium">{rec.mooringNumber}</span>
                    {rec.area && (
                      <span className="text-xs text-muted-foreground">{rec.area}</span>
                    )}
                    <Badge
                      variant={rec.source === 'ai' ? 'secondary' : 'outline'}
                      className="text-xs"
                    >
                      {rec.source === 'ai' ? 'AI' : 'Manual'}
                    </Badge>
                  </div>

                  {rec.matchScore && (
                    <div className="flex items-center gap-2">
                      <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                        <div
                          className="h-full bg-primary rounded-full"
                          style={{ width: `${score}%` }}
                        />
                      </div>
                      <span className="text-xs text-muted-foreground w-8">{score}%</span>
                    </div>
                  )}

                  {(rec.lengthFt || rec.widthFt) && (
                    <p className="text-xs text-muted-foreground mt-1">
                      {rec.lengthFt && `${rec.lengthFt}ft length`}
                      {rec.lengthFt && rec.widthFt && ' · '}
                      {rec.widthFt && `${rec.widthFt}ft beam`}
                    </p>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
