"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { Plus } from "lucide-react";
import { apiGet, apiSend } from "@/lib/api";
import type { AppraisalListItem, UserDTO } from "@/lib/types";
import { can } from "@/lib/rbac";
import {
  APPRAISAL_HALF_LABEL,
  APPRAISAL_STATUS_LABEL,
  APPRAISAL_STATUS_BADGE,
  APPRAISAL_BAND_LABEL,
  APPRAISAL_BAND_BADGE,
} from "@/lib/labels";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogHeader, DialogBody, DialogFooter } from "@/components/ui/dialog";
import { PageHeader, Spinner, EmptyState } from "@/components/common";

export function AppraisalsView() {
  const { data: session } = useSession();
  const canManage = can(session?.user?.role, "appraisals:manage");
  const [open, setOpen] = React.useState(false);

  const q = useQuery({
    queryKey: ["appraisals"],
    queryFn: () => apiGet<AppraisalListItem[]>("/api/appraisals"),
  });

  const list = q.data ?? [];

  return (
    <div>
      <PageHeader title="Staff Appraisals" subtitle="Half-year performance reviews">
        {canManage && (
          <Button onClick={() => setOpen(true)}>
            <Plus className="size-4" /> New Appraisal
          </Button>
        )}
      </PageHeader>

      {q.isLoading ? (
        <Spinner />
      ) : list.length === 0 ? (
        <EmptyState
          title="No appraisals yet"
          description={canManage ? "Create a half-year appraisal for a staff member." : "Your appraisals will appear here."}
        />
      ) : (
        <Card className="overflow-hidden">
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border text-left text-xs uppercase text-muted-foreground">
                    <th className="px-4 py-2.5">Staff</th>
                    <th className="px-4 py-2.5">Period</th>
                    <th className="px-4 py-2.5">Status</th>
                    <th className="px-4 py-2.5">Overall</th>
                    <th className="px-4 py-2.5">Reviewer</th>
                  </tr>
                </thead>
                <tbody>
                  {list.map((a) => (
                    <tr
                      key={a.id}
                      className="cursor-pointer border-b border-border last:border-0 hover:bg-secondary/50"
                      onClick={() => (window.location.href = `/appraisals/${a.id}`)}
                    >
                      <td className="px-4 py-2.5">
                        <Link href={`/appraisals/${a.id}`} className="font-medium hover:underline">
                          {a.user.name}
                        </Link>
                        {a.user.position && (
                          <div className="text-xs text-muted-foreground">{a.user.position}</div>
                        )}
                      </td>
                      <td className="px-4 py-2.5">
                        {APPRAISAL_HALF_LABEL[a.half]} {a.year}
                      </td>
                      <td className="px-4 py-2.5">
                        <Badge variant={APPRAISAL_STATUS_BADGE[a.status]}>
                          {APPRAISAL_STATUS_LABEL[a.status]}
                        </Badge>
                      </td>
                      <td className="px-4 py-2.5">
                        {a.overallBand ? (
                          <Badge variant={APPRAISAL_BAND_BADGE[a.overallBand]}>
                            {APPRAISAL_BAND_LABEL[a.overallBand]}
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground">—</span>
                        )}
                      </td>
                      <td className="px-4 py-2.5 text-muted-foreground">{a.reviewer?.name ?? "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}

      {canManage && <NewAppraisalDialog open={open} onClose={() => setOpen(false)} />}
    </div>
  );
}

function NewAppraisalDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
  const qc = useQueryClient();
  const router = useRouter();
  const today = new Date();
  const [userId, setUserId] = React.useState("");
  const [year, setYear] = React.useState(today.getFullYear());
  const [half, setHalf] = React.useState(today.getMonth() + 1 <= 6 ? "H1" : "H2");
  const [error, setError] = React.useState("");

  const usersQuery = useQuery({
    queryKey: ["users"],
    queryFn: () => apiGet<UserDTO[]>("/api/users"),
    enabled: open,
  });
  const staff = (usersQuery.data ?? []).filter((u) => u.role === "STAFF");
  const years = [today.getFullYear() - 1, today.getFullYear(), today.getFullYear() + 1];

  const create = useMutation({
    mutationFn: () =>
      apiSend<{ id: string; error?: string }>("/api/appraisals", "POST", { userId, year, half }),
    onSuccess: (res) => {
      if (res?.error) {
        setError(res.error);
        return;
      }
      qc.invalidateQueries({ queryKey: ["appraisals"] });
      onClose();
      if (res?.id) router.push(`/appraisals/${res.id}`);
    },
    onError: (e) => setError(e instanceof Error ? e.message : "Failed to create"),
  });

  return (
    <Dialog open={open} onClose={onClose} className="max-w-md">
      <DialogHeader title="New Appraisal" onClose={onClose} />
      <DialogBody>
        <div className="space-y-1.5">
          <Label>Staff member</Label>
          <Select value={userId} onChange={(e) => setUserId(e.target.value)}>
            <option value="">— Select staff —</option>
            {staff.map((u) => (
              <option key={u.id} value={u.id}>
                {u.name}
                {u.position ? ` · ${u.position}` : ""}
              </option>
            ))}
          </Select>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1.5">
            <Label>Period</Label>
            <Select value={half} onChange={(e) => setHalf(e.target.value)}>
              <option value="H1">H1 (Jan–Jun)</option>
              <option value="H2">H2 (Jul–Dec)</option>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label>Year</Label>
            <Select value={String(year)} onChange={(e) => setYear(Number(e.target.value))}>
              {years.map((y) => (
                <option key={y} value={y}>{y}</option>
              ))}
            </Select>
          </div>
        </div>
        {error && <p className="text-sm text-destructive">{error}</p>}
      </DialogBody>
      <DialogFooter>
        <Button type="button" variant="secondary" onClick={onClose}>
          Cancel
        </Button>
        <Button type="button" disabled={!userId || create.isPending} onClick={() => create.mutate()}>
          Create &amp; open
        </Button>
      </DialogFooter>
    </Dialog>
  );
}
