"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { ArrowUpRight, FileText, FolderKanban, Link2, Trash2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import type { NoteRelation, RelatedKnowledgeNote } from "@/types";

type NoteOption = { id: string; title: string };
type TaskOption = { id: string; title: string };
type ProjectOption = { id: string; name: string; icon?: string | null };

interface NoteKnowledgeProps {
  outbound: NoteRelation[];
  backlinks: NoteRelation[];
  relatedNotes: RelatedKnowledgeNote[];
  loading: boolean;
  noteOptions: NoteOption[];
  taskOptions: TaskOption[];
  projectOptions: ProjectOption[];
  onAddRelation: (input: {
    targetType: NoteRelation["target_type"];
    targetId: string;
  }) => Promise<void>;
  onDeleteRelation: (id: string) => Promise<void>;
  disabled?: boolean;
}

export function NoteKnowledge(props: NoteKnowledgeProps) {
  const {
    outbound,
    backlinks,
    relatedNotes,
    loading,
    noteOptions,
    taskOptions,
    projectOptions,
    onAddRelation,
    onDeleteRelation,
    disabled = false,
  } = props;

  const [targetType, setTargetType] = useState<NoteRelation["target_type"]>("note");
  const [targetId, setTargetId] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const targetOptions = useMemo(() => {
    if (targetType === "note") {
      return noteOptions.map((note) => ({ id: note.id, label: note.title }));
    }

    if (targetType === "task") {
      return taskOptions.map((task) => ({ id: task.id, label: task.title }));
    }

    return projectOptions.map((project) => ({
      id: project.id,
      label: `${project.icon || "📁"} ${project.name}`,
    }));
  }, [noteOptions, projectOptions, targetType, taskOptions]);

  async function handleAddRelation() {
    if (!targetId || submitting) return;

    setSubmitting(true);
    try {
      await onAddRelation({ targetType, targetId });
      setTargetId("");
    } finally {
      setSubmitting(false);
    }
  }

  function renderRelationTitle(relation: NoteRelation) {
    if (relation.target_type === "note") {
      return relation.target_note?.title || "Linked note";
    }
    if (relation.target_type === "task") {
      return relation.target_task?.title || "Linked task";
    }
    return relation.target_project?.name || "Linked project";
  }

  function renderRelationHref(relation: NoteRelation) {
    if (relation.target_type === "note" && relation.target_note?.id) {
      return `/notes/${relation.target_note.id}`;
    }
    if (relation.target_type === "task" && relation.target_task?.id) {
      return "/tasks";
    }
    if (relation.target_type === "project" && relation.target_project?.id) {
      return `/projects/${relation.target_project.id}`;
    }
    return "#";
  }

  return (
    <Card className="mt-6">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-base">
          <Link2 className="h-4 w-4" />
          Knowledge Graph
        </CardTitle>
        <CardDescription>
          Link this note to other notes, tasks, and projects, then use backlinks and related notes
          to move through the knowledge around it.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        <div className="grid gap-4 md:grid-cols-[140px,1fr,auto]">
          <div className="space-y-2">
            <Label>Type</Label>
            <Select
              value={targetType}
              onChange={(event) => {
                setTargetType(event.target.value as NoteRelation["target_type"]);
                setTargetId("");
              }}
              disabled={disabled}
            >
              <option value="note">Note</option>
              <option value="task">Task</option>
              <option value="project">Project</option>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Link target</Label>
            <Select
              value={targetId}
              onChange={(event) => setTargetId(event.target.value)}
              disabled={disabled}
            >
              <option value="">Choose a target</option>
              {targetOptions.map((option) => (
                <option key={`${targetType}-${option.id}`} value={option.id}>
                  {option.label}
                </option>
              ))}
            </Select>
          </div>
          <div className="flex items-end">
            <Button onClick={() => void handleAddRelation()} disabled={!targetId || disabled || submitting}>
              {submitting ? "Linking..." : "Add link"}
            </Button>
          </div>
        </div>

        <div className="grid gap-6 lg:grid-cols-2">
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-medium">References</h3>
              <Badge variant="outline">{outbound.length}</Badge>
            </div>
            {loading ? (
              <p className="text-sm text-muted-foreground">Loading knowledge links...</p>
            ) : outbound.length === 0 ? (
              <EmptyState
                title="No references yet"
                description="Link this note to a task, project, or another note to turn it into connected knowledge."
              />
            ) : (
              <div className="space-y-3">
                {outbound.map((relation) => (
                  <div
                    key={relation.id}
                    className="rounded-xl border border-border/60 bg-background/60 p-3"
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="space-y-2">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline">{relation.target_type}</Badge>
                          <Link
                            href={renderRelationHref(relation)}
                            className="text-sm font-medium hover:underline"
                          >
                            {renderRelationTitle(relation)}
                          </Link>
                        </div>
                        <p className="text-xs text-muted-foreground">
                          Added {new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(new Date(relation.created_at))}
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Link href={renderRelationHref(relation)}>
                          <Button variant="ghost" size="icon">
                            <ArrowUpRight className="h-4 w-4" />
                          </Button>
                        </Link>
                        {!disabled && (
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => void onDeleteRelation(relation.id)}
                          >
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-medium">Backlinks</h3>
              <Badge variant="outline">{backlinks.length}</Badge>
            </div>
            {loading ? (
              <p className="text-sm text-muted-foreground">Loading backlinks...</p>
            ) : backlinks.length === 0 ? (
              <EmptyState
                title="No backlinks yet"
                description="As soon as other notes point to this one, they will show up here."
              />
            ) : (
              <div className="space-y-3">
                {backlinks.map((relation) => (
                  <Link
                    key={relation.id}
                    href={relation.source_note?.id ? `/notes/${relation.source_note.id}` : "#"}
                    className="block rounded-xl border border-border/60 bg-background/60 p-3 hover:bg-accent/30"
                  >
                    <div className="flex items-center gap-2">
                      <FileText className="h-4 w-4 text-muted-foreground" />
                      <span className="text-sm font-medium">
                        {relation.source_note?.title || "Linked note"}
                      </span>
                    </div>
                    <p className="mt-2 text-xs text-muted-foreground">
                      Refers to this note
                    </p>
                  </Link>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-medium">Related notes</h3>
            <Badge variant="outline">{relatedNotes.length}</Badge>
          </div>
          {loading ? (
            <p className="text-sm text-muted-foreground">Looking for related notes...</p>
          ) : relatedNotes.length === 0 ? (
            <EmptyState
              title="No related notes yet"
              description="Notes from the same project or with overlapping tags will show up here."
            />
          ) : (
            <div className="grid gap-3 md:grid-cols-2">
              {relatedNotes.map((note) => (
                <div
                  key={note.id}
                  className="rounded-xl border border-border/60 bg-background/60 p-3"
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="space-y-2">
                      <Link href={`/notes/${note.id}`} className="text-sm font-medium hover:underline">
                        {note.title}
                      </Link>
                      <div className="flex flex-wrap gap-2">
                        {note.reasons.map((reason) => (
                          <Badge key={`${note.id}-${reason}`} variant="secondary">
                            {reason}
                          </Badge>
                        ))}
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Link href={`/notes/${note.id}`}>
                        <Button variant="ghost" size="icon">
                          <ArrowUpRight className="h-4 w-4" />
                        </Button>
                      </Link>
                      {!disabled && (
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => void onAddRelation({ targetType: "note", targetId: note.id })}
                        >
                          <FolderKanban className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}
