"use client";

import { useRef, useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/components/ui/card";
import {
  Table,
  TableHeader,
  TableBody,
  TableHead,
  TableRow,
  TableCell,
} from "@/components/ui/table";
import { DOCUMENT_STATUSES } from "@/lib/applications/constants";
import type { ApplicationDocument } from "@/lib/types";
import { uploadStudentDocument } from "./actions";

export type DocumentWithUrl = ApplicationDocument & {
  signedUrl: string | null;
};

const STATUS_VARIANT: Record<
  (typeof DOCUMENT_STATUSES)[number],
  "secondary" | "default" | "destructive"
> = {
  pending: "secondary",
  verified: "default",
  rejected: "destructive",
};

function StatusBadge({ status }: { status: string }) {
  const variant =
    (STATUS_VARIANT as Record<string, "secondary" | "default" | "destructive">)[
      status
    ] ?? "secondary";
  return (
    <Badge variant={variant} className="capitalize">
      {status}
    </Badge>
  );
}

/* -------------------------------------------------------------------------- */
/* Upload form                                                                */
/* -------------------------------------------------------------------------- */

function UploadForm({ applicationId }: { applicationId: string }) {
  const formRef = useRef<HTMLFormElement>(null);
  const [pending, startTransition] = useTransition();

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const file = formData.get("file");
    if (!(file instanceof File) || file.size === 0) {
      toast.error("Please choose a file to upload");
      return;
    }
    startTransition(async () => {
      const res = await uploadStudentDocument(applicationId, formData);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("Document uploaded");
        formRef.current?.reset();
      }
    });
  }

  return (
    <form ref={formRef} onSubmit={onSubmit} className="space-y-4">
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor="doc-file">File</Label>
          <Input id="doc-file" name="file" type="file" required />
        </div>
        <div className="space-y-2">
          <Label htmlFor="doc-name">Name (optional)</Label>
          <Input
            id="doc-name"
            name="name"
            placeholder="Defaults to file name"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="doc-type">Type (optional)</Label>
          <Input
            id="doc-type"
            name="doc_type"
            placeholder="e.g. Passport, Transcript"
          />
        </div>
      </div>
      <Button type="submit" disabled={pending}>
        {pending ? "Uploading…" : "Upload document"}
      </Button>
    </form>
  );
}

/* -------------------------------------------------------------------------- */
/* Main client component                                                      */
/* -------------------------------------------------------------------------- */

export function DocumentsClient({
  applicationId,
  documents,
}: {
  applicationId: string;
  documents: DocumentWithUrl[];
}) {
  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Upload a document</CardTitle>
        </CardHeader>
        <CardContent>
          <UploadForm applicationId={applicationId} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Your documents</CardTitle>
        </CardHeader>
        <CardContent>
          {documents.length === 0 ? (
            <p className="text-sm text-muted-foreground">
              No documents uploaded yet.
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">File</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {documents.map((doc) => (
                  <TableRow key={doc.id}>
                    <TableCell className="font-medium">{doc.name}</TableCell>
                    <TableCell>{doc.doc_type ?? "—"}</TableCell>
                    <TableCell>
                      <StatusBadge status={doc.status} />
                    </TableCell>
                    <TableCell className="text-right">
                      {doc.signedUrl ? (
                        <a
                          href={doc.signedUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-brand-blue underline underline-offset-4"
                        >
                          Download
                        </a>
                      ) : (
                        <span className="text-muted-foreground">
                          Unavailable
                        </span>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
