"use client";

import { use, useState } from "react";
import { useRouter } from "next/navigation";
import { trpc } from "@/trpc/client";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { PrintExportButton } from "@/components/print-export/print-export-button";
import { formatCurrency, formatDate } from "@/lib/print-export";

interface Weights {
  price: number;
  completeness: number;
  pastPerf: number;
}

interface VendorScore {
  id: string;
  name: string;
  submissionId: string;
  filledItems: number;
  totalItems: number;
  completenessScore: number;
  awardCount: number;
  totalQuoted: number;
  priceScore: number;
  pastPerfScore: number;
  composite: number;
}

function WeightInput({
  label,
  value,
  onChange,
}: {
  label: string;
  value: number;
  onChange: (v: number) => void;
}) {
  return (
    <div className="flex items-center gap-2">
      <span className="w-32 text-sm">{label}</span>
      <Input
        type="number"
        min={0}
        max={100}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className="w-20 text-center"
      />
      <span className="text-muted-foreground text-sm">%</span>
    </div>
  );
}

export default function AnalysisPage({
  params,
}: {
  params: Promise<{ tenderId: string }>;
}) {
  const { tenderId } = use(params);
  const router = useRouter();

  const { data, isLoading } = trpc.analysis.generate.useQuery({ tenderId });
  const { data: existing } = trpc.analysis.getByTender.useQuery({ tenderId });

  const createMutation = trpc.analysis.create.useMutation({
    onSuccess: () => toast.success("Analysis saved"),
    onError: (err) => toast.error(err.message),
  });
  const submitToBoard = trpc.analysis.submitToBoard.useMutation({
    onSuccess: () => {
      toast.success("Submitted to board for review");
      router.push(`/tenders/${tenderId}`);
    },
    onError: (err) => toast.error(err.message),
  });

  const [weights, setWeights] = useState<Weights>({
    price: 60,
    completeness: 25,
    pastPerf: 15,
  });
  const [annotation, setAnnotation] = useState({
    findings: existing?.recommendation ?? "",
    conditions: existing?.conditions ?? "",
    recommendation: "",
  });

  const weightTotal = weights.price + weights.completeness + weights.pastPerf;

  if (isLoading) return <div className="p-8">Loading analysis...</div>;
  if (!data) return <div className="p-8">Tender not found</div>;

  const { matrix, tender } = data;
  const vendors: Omit<VendorScore, "composite">[] = data.vendors;

  // Compute composite scores with current weights
  const scored: VendorScore[] = vendors
    .map((v) => {
      const composite =
        (v.priceScore * weights.price) / 100 +
        (v.completenessScore * weights.completeness) / 100 +
        (v.pastPerfScore * weights.pastPerf) / 100;
      return { ...v, composite };
    })
    .sort((a, b) => b.composite - a.composite);

  const analysisExportData = scored.map((v, idx) => ({
    Rank: idx + 1,
    Vendor: v.name,
    "Total Quoted": v.totalQuoted,
    "Price Score": v.priceScore.toFixed(1),
    Completeness: `${v.completenessScore.toFixed(1)}%`,
    "Past Perf.": v.pastPerfScore.toFixed(1),
    Composite: v.composite.toFixed(2),
  }));

  const analysisColumns = [
    { header: "Rank", key: "Rank", align: "center" as const },
    { header: "Vendor", key: "Vendor" },
    {
      header: "Total Quoted (NPR)",
      key: "Total Quoted",
      align: "right" as const,
      formatter: formatCurrency,
    },
    { header: "Price Score", key: "Price Score", align: "right" as const },
    { header: "Completeness", key: "Completeness", align: "right" as const },
    { header: "Past Perf.", key: "Past Perf.", align: "right" as const },
    { header: "Composite Score", key: "Composite", align: "right" as const },
  ];

  const vendorIds = vendors.map((v) => v.id);

  const handleSave = () => {
    createMutation.mutate({
      tenderId,
      analysisData: { matrix, vendors: scored, weights },
      recommendation: annotation.findings || undefined,
      conditions: annotation.conditions || undefined,
    });
  };

  const handleSubmitToBoard = () => {
    if (!existing) {
      toast.error("Save the analysis first before submitting to board");
      return;
    }
    submitToBoard.mutate({
      analysisId: existing.id,
      recommendation: annotation.recommendation || annotation.findings || "",
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-bold">Comparative Analysis</h1>
          <p className="text-muted-foreground">
            {tender.referenceNo} — {tender.title}
          </p>
        </div>
        <div className="no-print flex gap-2">
          <Button
            variant="outline"
            onClick={handleSave}
            disabled={createMutation.isPending}
          >
            {createMutation.isPending ? "Saving..." : "Save Analysis"}
          </Button>
          <Button
            onClick={handleSubmitToBoard}
            disabled={submitToBoard.isPending || !existing}
          >
            {submitToBoard.isPending ? "Submitting..." : "Submit to Board"}
          </Button>
        </div>
      </div>

      <div className="no-print flex gap-2">
        <PrintExportButton
          title={`Analysis - ${tender.referenceNo}`}
          subtitle={tender.title}
          data={analysisExportData}
          columns={analysisColumns}
          filename={`Analysis_${tender.referenceNo}_${new Date().toISOString().split("T")[0]}.pdf`}
        />
      </div>

      {/* Scoring weights */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-3">
            Scoring Weights
            {weightTotal !== 100 && (
              <Badge variant="destructive">
                Total: {weightTotal}% (must equal 100%)
              </Badge>
            )}
            {weightTotal === 100 && (
              <Badge variant="default">Total: 100%</Badge>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent className="flex flex-wrap gap-6">
          <WeightInput
            label="Price"
            value={weights.price}
            onChange={(v) => setWeights((w) => ({ ...w, price: v }))}
          />
          <WeightInput
            label="Completeness"
            value={weights.completeness}
            onChange={(v) => setWeights((w) => ({ ...w, completeness: v }))}
          />
          <WeightInput
            label="Past Performance"
            value={weights.pastPerf}
            onChange={(v) => setWeights((w) => ({ ...w, pastPerf: v }))}
          />
        </CardContent>
      </Card>

      {/* Vendor ranking */}
      <Card>
        <CardHeader>
          <CardTitle>Vendor Ranking</CardTitle>
        </CardHeader>
        <CardContent>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b">
                <th className="pb-2 text-left">Rank</th>
                <th className="pb-2 text-left">Vendor</th>
                <th className="pb-2 text-right">Total Quoted</th>
                <th className="pb-2 text-right">Price Score</th>
                <th className="pb-2 text-right">Completeness</th>
                <th className="pb-2 text-right">Past Perf.</th>
                <th className="pb-2 text-right font-bold">Composite Score</th>
              </tr>
            </thead>
            <tbody>
              {scored.map((v, i) => (
                <tr
                  key={v.id}
                  className={cn(
                    "border-b",
                    i === 0 && "bg-green-50 font-medium",
                  )}
                >
                  <td className="py-2">
                    {i === 0 ? (
                      <Badge className="bg-green-600">
                        #{i + 1} Recommended
                      </Badge>
                    ) : (
                      <span className="text-muted-foreground">#{i + 1}</span>
                    )}
                  </td>
                  <td className="py-2">{v.name}</td>
                  <td className="py-2 text-right font-mono">
                    NPR {v.totalQuoted.toLocaleString()}
                  </td>
                  <td className="py-2 text-right">{v.priceScore.toFixed(1)}</td>
                  <td className="py-2 text-right">
                    {v.completenessScore.toFixed(1)}%
                    {v.filledItems < v.totalItems && (
                      <span className="text-muted-foreground ml-1 text-xs">
                        ({v.filledItems}/{v.totalItems})
                      </span>
                    )}
                  </td>
                  <td className="py-2 text-right">
                    {v.pastPerfScore.toFixed(1)}
                    <span className="text-muted-foreground ml-1 text-xs">
                      ({v.awardCount} awards)
                    </span>
                  </td>
                  <td className="py-2 text-right text-base font-bold">
                    {v.composite.toFixed(2)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </CardContent>
      </Card>

      {/* Matrix */}
      <Card>
        <CardHeader>
          <CardTitle>Item-wise Price Comparison</CardTitle>
          <div className="flex gap-4 text-xs">
            <span className="flex items-center gap-1">
              <span className="inline-block h-3 w-3 rounded bg-green-200" />{" "}
              Lowest
            </span>
            <span className="flex items-center gap-1">
              <span className="inline-block h-3 w-3 rounded bg-yellow-200" />{" "}
              Median
            </span>
            <span className="flex items-center gap-1">
              <span className="inline-block h-3 w-3 rounded bg-red-200" />{" "}
              Highest
            </span>
          </div>
        </CardHeader>
        <CardContent className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b">
                <th className="pb-2 text-left">Item</th>
                <th className="pb-2 text-left">Unit</th>
                <th className="pb-2 text-right">Qty</th>
                <th className="pb-2 text-right">Rate</th>
                {vendors.map((v) => (
                  <th key={v.id} className="pb-2 text-right">
                    {v.name}
                  </th>
                ))}
                <th className="pb-2 text-right text-green-700">Lowest</th>
                <th className="pb-2 text-right text-yellow-700">Median</th>
                <th className="pb-2 text-right text-red-700">Highest</th>
              </tr>
            </thead>
            <tbody>
              {matrix.map((row) => {
                const estRate = row.estimatedRate;
                return (
                  <tr key={row.itemId} className="border-b">
                    <td className="py-2 font-medium">
                      <span className="text-muted-foreground font-mono text-xs">
                        {row.itemCode}
                      </span>{" "}
                      {row.itemName}
                    </td>
                    <td className="text-muted-foreground py-2">{row.unit}</td>
                    <td className="py-2 text-right">{row.quantity}</td>
                    <td className="py-2 text-right">
                      {estRate ? `NPR ${estRate.toLocaleString()}` : "-"}
                    </td>
                    {vendorIds.map((vid) => {
                      const bid = row.bids.find((b) => b.vendorId === vid);
                      const rate = bid?.quotedRate;
                      const isLowest =
                        rate !== null &&
                        rate !== undefined &&
                        row.lowest != null &&
                        rate === row.lowest;
                      const isHighest =
                        rate !== null &&
                        rate !== undefined &&
                        row.highest != null &&
                        rate === row.highest;
                      const rowMedian = row.median ?? 0;
                      const isMedian =
                        rate !== null &&
                        rate !== undefined &&
                        !isLowest &&
                        !isHighest &&
                        rowMedian > 0 &&
                        Math.abs(rate - rowMedian) / rowMedian < 0.02;
                      const deviation =
                        estRate && rate
                          ? ((rate - estRate) / estRate) * 100
                          : null;
                      return (
                        <td
                          key={vid}
                          className={cn(
                            "py-2 text-right",
                            isLowest &&
                              "bg-green-100 font-semibold text-green-800",
                            isHighest &&
                              "bg-red-100 font-semibold text-red-800",
                            isMedian && "bg-yellow-100 text-yellow-800",
                            rate === null || rate === undefined
                              ? "text-muted-foreground"
                              : "",
                          )}
                        >
                          {rate !== null && rate !== undefined ? (
                            <div>
                              <div>NPR {rate.toLocaleString()}</div>
                              {deviation !== null && (
                                <div
                                  className={cn(
                                    "text-xs",
                                    deviation > 0
                                      ? "text-red-500"
                                      : "text-green-600",
                                  )}
                                >
                                  {deviation > 0 ? "+" : ""}
                                  {deviation.toFixed(1)}%
                                </div>
                              )}
                            </div>
                          ) : (
                            "—"
                          )}
                        </td>
                      );
                    })}
                    <td className="py-2 text-right font-semibold text-green-700">
                      {row.lowest != null
                        ? `NPR ${row.lowest.toLocaleString()}`
                        : "—"}
                    </td>
                    <td className="py-2 text-right text-yellow-700">
                      {(row.median ?? 0) > 0
                        ? `NPR ${(row.median ?? 0).toLocaleString()}`
                        : "—"}
                    </td>
                    <td className="py-2 text-right font-semibold text-red-700">
                      {row.highest != null
                        ? `NPR ${row.highest.toLocaleString()}`
                        : "—"}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </CardContent>
      </Card>

      {/* Admin annotation */}
      <Card>
        <CardHeader>
          <CardTitle>Admin Annotation</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label>Findings</Label>
            <Textarea
              className="mt-1"
              rows={3}
              placeholder="Key findings from the comparison, notable deviations, anomalies..."
              value={annotation.findings}
              onChange={(e) =>
                setAnnotation((a) => ({ ...a, findings: e.target.value }))
              }
            />
          </div>
          <div>
            <Label>Conditions</Label>
            <Textarea
              className="mt-1"
              rows={3}
              placeholder="Any conditions or requirements the recommended vendor must comply with..."
              value={annotation.conditions}
              onChange={(e) =>
                setAnnotation((a) => ({ ...a, conditions: e.target.value }))
              }
            />
          </div>
          <div>
            <Label>Narrative Recommendation (for board)</Label>
            <Textarea
              className="mt-1"
              rows={4}
              placeholder="Summarise the recommendation and justification for the board..."
              value={annotation.recommendation}
              onChange={(e) =>
                setAnnotation((a) => ({ ...a, recommendation: e.target.value }))
              }
            />
          </div>
        </CardContent>
      </Card>

      <div className="no-print flex justify-end gap-2">
        <Button
          variant="outline"
          onClick={handleSave}
          disabled={createMutation.isPending}
        >
          {createMutation.isPending ? "Saving..." : "Save Analysis"}
        </Button>
        <Button
          onClick={handleSubmitToBoard}
          disabled={submitToBoard.isPending || !existing}
        >
          {submitToBoard.isPending ? "Submitting..." : "Submit to Board →"}
        </Button>
      </div>
    </div>
  );
}
