"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { scoreMatchBreakdown } from "@/lib/scoring";
import type { Property, PropertyMatch, CustomerSearch } from "@/lib/appwrite/schema";

interface Props {
  match: PropertyMatch;
  property: Property | undefined;
  search: CustomerSearch | undefined;
  customerName: string;
  propertyTitle: string;
  open: boolean;
  onOpenChange: (v: boolean) => void;
}

export function MatchBreakdownDialog({
  match,
  property,
  search,
  customerName,
  propertyTitle,
  open,
  onOpenChange,
}: Props) {
  const breakdown =
    property && search ? scoreMatchBreakdown(property, search) : null;

  const pctColor = (r: number) =>
    r >= 0.8
      ? "text-green-600"
      : r >= 0.5
        ? "text-blue-600"
        : r >= 0.3
          ? "text-yellow-600"
          : "text-red-500";

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Eşleşme Detayı</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="flex items-center justify-between rounded-lg bg-muted/50 px-4 py-3">
            <div>
              <p className="font-semibold">{customerName}</p>
              <p className="text-muted-foreground text-sm">{propertyTitle}</p>
            </div>
            <ScoreCircle score={match.score ?? 0} />
          </div>

          {!breakdown && (
            <p className="text-muted-foreground text-sm">Kırılım verisi bulunamadı.</p>
          )}

          {breakdown && (
            <>
              {breakdown.criteria.length === 0 ? (
                <p className="text-muted-foreground text-sm">
                  Bu aramada kriter belirtilmemiş — her ilan 100 puan alır.
                </p>
              ) : (
                <div className="space-y-2">
                  {breakdown.criteria.map((c) => (
                    <div key={c.label} className="grid grid-cols-[1fr_auto_auto] items-start gap-3">
                      <div>
                        <div className="flex items-center gap-1.5 text-sm font-medium">
                          <span>{c.label}</span>
                          <span className="text-muted-foreground text-xs">(ağırlık: {c.weight})</span>
                        </div>
                        <p className="text-muted-foreground text-xs mt-0.5">{c.note}</p>
                      </div>
                      <div className="text-right">
                        <span className={`text-sm font-semibold ${pctColor(c.ratio)}`}>
                          %{Math.round(c.ratio * 100)}
                        </span>
                      </div>
                      <div className="text-right">
                        <span className="text-muted-foreground text-xs">
                          {c.earned.toFixed(1)}/{c.weight}
                        </span>
                      </div>
                    </div>
                  ))}

                  <div className="border-t pt-2 grid grid-cols-[1fr_auto_auto] gap-3">
                    <span className="text-sm font-semibold">Toplam</span>
                    <span className="text-right text-sm font-semibold">
                      %{breakdown.score}
                    </span>
                    <span className="text-right text-xs text-muted-foreground">
                      {breakdown.total.toFixed(1)}/{breakdown.maxPossible}
                    </span>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

function ScoreCircle({ score }: { score: number }) {
  const color =
    score >= 80
      ? "bg-green-100 text-green-700"
      : score >= 60
        ? "bg-blue-100 text-blue-700"
        : score >= 40
          ? "bg-yellow-100 text-yellow-700"
          : "bg-gray-100 text-gray-500";
  return (
    <span
      className={`inline-flex size-12 shrink-0 items-center justify-center rounded-full text-lg font-bold ${color}`}
    >
      {score}
    </span>
  );
}
