"use client";

import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { getClient } from "@/lib/api/client";
import { useProjectPath } from "@/lib/hooks/useProjectPath";
import type {
  AuthoredClaimDto,
  ListClaimsResponse,
  VerifyReportResponse,
  CoverageReportResponse,
} from "@/lib/api/types";
import { ClaimsLoadingSkeleton } from "./claims-loading-skeleton";
import { ClaimsEmptyState } from "./claims-empty-state";
import { ClaimCard } from "./claim-card";

type PanelState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: string };

export function ClaimsPanel() {
  const { projectPath } = useProjectPath();
  const [claimsState, setClaimsState] = useState<PanelState<ListClaimsResponse>>({
    status: "idle",
  });
  const [verifyState, setVerifyState] = useState<PanelState<VerifyReportResponse>>({
    status: "idle",
  });
  const [coverageState, setCoverageState] = useState<PanelState<CoverageReportResponse>>({
    status: "idle",
  });
  const [selectedClaim, setSelectedClaim] = useState<AuthoredClaimDto | null>(null);

  const client = getClient();

  const loadClaims = async () => {
    if (!projectPath.trim()) {
      setClaimsState({
        status: "error",
        error: "Please set a project path in the sidebar",
      });
      return;
    }

    setClaimsState({ status: "loading" });
    try {
      const data = await client.listClaims({ project_path: projectPath });
      setClaimsState({ status: "success", data });
    } catch (error) {
      setClaimsState({
        status: "error",
        error: error instanceof Error ? error.message : "Failed to load claims",
      });
    }
  };

  const runVerification = async () => {
    if (!projectPath.trim()) {
      setVerifyState({
        status: "error",
        error: "Please set a project path in the sidebar",
      });
      return;
    }

    setVerifyState({ status: "loading" });
    try {
      const data = await client.verifyClaims({ project_path: projectPath });
      setVerifyState({ status: "success", data });
    } catch (error) {
      setVerifyState({
        status: "error",
        error: error instanceof Error ? error.message : "Verification failed",
      });
    }
  };

  const loadCoverage = async () => {
    if (!projectPath.trim()) {
      setCoverageState({
        status: "error",
        error: "Please set a project path in the sidebar",
      });
      return;
    }

    setCoverageState({ status: "loading" });
    try {
      const data = await client.getCoverage({ project_path: projectPath });
      setCoverageState({ status: "success", data });
    } catch (error) {
      setCoverageState({
        status: "error",
        error: error instanceof Error ? error.message : "Coverage load failed",
      });
    }
  };

  return (
    <div className="space-y-6">
      {/* Project Path Display */}
      <Card>
        <CardHeader>
          <CardTitle>Project Configuration</CardTitle>
          <CardDescription>
            Project path: <span className="font-mono">{projectPath || "Not set (configure in sidebar)"}</span>
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Button onClick={loadClaims} disabled={!projectPath.trim()}>
            Load Claims
          </Button>
        </CardContent>
      </Card>

      {/* Tabs for Claims / Verify / Coverage */}
      <Tabs defaultValue="claims" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="claims">Claims List</TabsTrigger>
          <TabsTrigger value="verify">Verification</TabsTrigger>
          <TabsTrigger value="coverage">Coverage</TabsTrigger>
        </TabsList>

        {/* Claims List Tab */}
        <TabsContent value="claims">
          {claimsState.status === "loading" && <ClaimsLoadingSkeleton />}
          {claimsState.status === "error" && (
            <Card>
              <CardContent className="pt-6">
                <p className="text-destructive">{claimsState.error}</p>
              </CardContent>
            </Card>
          )}
          {claimsState.status === "success" &&
            (claimsState.data.claims.length === 0 ? (
              <ClaimsEmptyState />
            ) : (
              <Card>
                <CardHeader>
                  <CardTitle>
                    Authored Claims ({claimsState.data.claims.length})
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {claimsState.data.claims.map((claim) => (
                      <ClaimCard
                        key={claim.id}
                        claim={claim}
                        onClick={() => setSelectedClaim(claim)}
                      />
                    ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          {claimsState.status === "idle" && (
            <Card>
              <CardContent className="pt-6">
                <p className="text-muted-foreground text-center">
                  Enter a project path and click "Load Claims" to begin
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* Verification Tab */}
        <TabsContent value="verify">
          <Card>
            <CardHeader>
              <CardTitle>Claim Verification</CardTitle>
              <CardDescription>
                Verify claims against extracted observations
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Button onClick={runVerification} disabled={verifyState.status === "loading"}>
                {verifyState.status === "loading" ? "Running..." : "Run Verification"}
              </Button>

              {verifyState.status === "success" && (
                <div className="space-y-4">
                  <div className="grid grid-cols-5 gap-4">
                    <div className="text-center">
                      <div className="text-2xl font-bold">{verifyState.data.summary.total_claims}</div>
                      <div className="text-sm text-muted-foreground">Total</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-green-600">
                        {verifyState.data.summary.pass}
                      </div>
                      <div className="text-sm text-muted-foreground">Pass</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-destructive">
                        {verifyState.data.summary.conflict}
                      </div>
                      <div className="text-sm text-muted-foreground">Conflict</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">{verifyState.data.summary.missing}</div>
                      <div className="text-sm text-muted-foreground">Missing</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">{verifyState.data.summary.unclaimed}</div>
                      <div className="text-sm text-muted-foreground">Unclaimed</div>
                    </div>
                  </div>
                </div>
              )}

              {verifyState.status === "error" && (
                <p className="text-destructive">{verifyState.error}</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Coverage Tab */}
        <TabsContent value="coverage">
          <Card>
            <CardHeader>
              <CardTitle>Coverage Metrics</CardTitle>
              <CardDescription>
                Per-module claim coverage analysis
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Button onClick={loadCoverage} disabled={coverageState.status === "loading"}>
                {coverageState.status === "loading" ? "Computing..." : "Compute Coverage"}
              </Button>

              {coverageState.status === "success" && (
                <div className="space-y-4">
                  <div className="grid grid-cols-3 gap-4">
                    <div className="text-center">
                      <div className="text-2xl font-bold">
                        {coverageState.data.summary.total_observations}
                      </div>
                      <div className="text-sm text-muted-foreground">Observations</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">
                        {coverageState.data.summary.total_claims}
                      </div>
                      <div className="text-sm text-muted-foreground">Claims</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">
                        {coverageState.data.summary.claimed_percentage.toFixed(1)}%
                      </div>
                      <div className="text-sm text-muted-foreground">Coverage</div>
                    </div>
                  </div>
                </div>
              )}

              {coverageState.status === "error" && (
                <p className="text-destructive">{coverageState.error}</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
