"use client";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
  ArrowLeft,
  FileText,
  ExternalLink,
  CheckCircle2,
  XCircle,
  ClipboardList,
  IndianRupee,
  Clock,
  RefreshCw,
} from "lucide-react";
import { getStatusVariant } from "@/lib/status-variant";
import { ClientDecideDialog } from "./ClientDecideDialog";
import { useGetTask } from "../hook/task.hook";
import { useTaskSocket } from "@/hooks/useTaskSocket";
import { useAppSelector } from "@/lib/store";
import { formatDateTime } from "@/lib/format-date";

const DOC_STATUS_STYLES: Record<string, string> = {
  APPROVED: "bg-green-500/15 text-green-700 border-green-200",
  VERIFIED: "bg-green-500/15 text-green-700 border-green-200",
  PENDING: "bg-yellow-500/15 text-yellow-700 border-yellow-200",
  REJECTED: "bg-red-500/15 text-red-700 border-red-200",
};

const PAY_STATUS: Record<
  string,
  {
    label: string;
    color: string;
    bg: string;
    border: string;
    icon: React.ReactNode;
  }
> = {
  SUCCESS: {
    label: "Success",
    color: "#fff",
    bg: "#16A34A",
    border: "#16A34A",
    icon: <CheckCircle2 size={11} />,
  },
  INITIATED: {
    label: "Pending",
    color: "#B45309",
    bg: "#FFFBEB",
    border: "#FCD34D",
    icon: <Clock size={11} />,
  },
  FAILED: {
    label: "Failed",
    color: "#DC2626",
    bg: "#FEF2F2",
    border: "#FCA5A5",
    icon: <XCircle size={11} />,
  },
  REFUNDED: {
    label: "Refunded",
    color: "#2563EB",
    bg: "#EFF6FF",
    border: "#93C5FD",
    icon: <RefreshCw size={11} />,
  },
};

function PayStatusPill({ status }: { status: string }) {
  const cfg = PAY_STATUS[status];
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        padding: "2px 8px",
        borderRadius: 9999,
        border: `1px solid ${cfg?.border ?? "#D1D5DB"}`,
        background: cfg?.bg ?? "#F3F4F6",
        color: cfg?.color ?? "#374151",
        fontSize: 10,
        fontWeight: 600,
        whiteSpace: "nowrap",
      }}
    >
      {cfg?.icon}
      {cfg?.label ?? status}
    </span>
  );
}

export function ClientTaskDetailPage() {
  const router = useRouter();
  const params = useParams<{ taskId: string }>();
  const taskId = params.taskId;
  const orgId = useAppSelector((s) => s.auth.user?.organizationId);
  useTaskSocket(orgId, ["tasks"]);

  const { data: taskResponse, isLoading } = useGetTask(taskId);
  const task = taskResponse?.data;
  const [decidingDecision, setDecidingDecision] = useState<
    "APPROVED" | "REJECTED" | null
  >(null);

  if (isLoading) {
    return (
      <div className="space-y-4 p-6">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-40 w-full rounded-lg" />
        <Skeleton className="h-40 w-full rounded-lg" />
      </div>
    );
  }

  if (!task) {
    return (
      <div className="flex flex-col items-center justify-center py-24 text-center gap-2">
        <div className="rounded-full bg-muted p-4">
          <ClipboardList className="h-8 w-8 text-muted-foreground/50" />
        </div>
        <p className="text-sm font-semibold text-muted-foreground">
          Task not found
        </p>
        <button
          onClick={() => router.back()}
          className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm"
        >
          <ArrowLeft className="h-4 w-4" /> Back
        </button>
      </div>
    );
  }

  const docs = task.documents ?? [];
  const canDecide = task.status === "CLIENT_APPROVAL";
  const invoice = task.invoice as any;
  const payments: any[] = invoice?.payments ?? [];

  return (
    <div className="space-y-6">
      <div>
        <button
          onClick={() => router.back()}
          className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm mt-3"
        >
          <ArrowLeft className="h-4 w-4" /> Back
        </button>
        <div>
          <h2 className="text-xl font-bold tracking-tight text-foreground">
            {task.title}
          </h2>
          <p className="text-muted-foreground text-xs mt-0.5">
            Task details and attached documents
          </p>
        </div>
      </div>

      {/* Task Info */}
      <Card className="border-border bg-card shadow-sm">
        <CardHeader className="border-b border-border px-6 py-4">
          <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            Task Info
          </p>
        </CardHeader>
        <CardContent className="px-6 py-5">
          <div className="grid grid-cols-2 gap-5 sm:grid-cols-3">
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                Category
              </p>
              <p className="mt-1 text-sm text-foreground">
                {task.service?.category ?? "—"}
              </p>
            </div>
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                Service
              </p>
              <p className="mt-1 text-sm text-foreground">
                {task.service?.name ?? "—"}
              </p>
            </div>
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                Status
              </p>
              <Badge
                variant={getStatusVariant(task.status)}
                className="mt-1 text-[10px]"
              >
                {task.status.replace(/_/g, " ")}
              </Badge>
            </div>
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                Priority
              </p>
              {task.priority ? (
                <Badge
                  variant={getStatusVariant(task.priority)}
                  className="mt-1 text-[10px]"
                >
                  {task.priority}
                </Badge>
              ) : (
                <p className="mt-1 text-sm text-muted-foreground">—</p>
              )}
            </div>
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                Created At
              </p>
              <p className="mt-1 text-sm text-foreground">
                {task.createdAt ? formatDateTime(task.createdAt) : "—"}
              </p>
            </div>
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                Note
              </p>
              <p className="mt-1 text-sm text-foreground">
                {task.description ?? "—"}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Invoice + Payment History */}
      {invoice && (
        <Card className="border-border bg-card shadow-sm">
          <CardHeader className="border-b border-border px-6 py-4">
            <div className="flex items-center justify-between">
              <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Invoice & Payments
              </p>
              <div className="flex items-center gap-2">
                <span className="text-xs font-mono text-muted-foreground">
                  {invoice.invoiceNumber}
                </span>
                <span
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 4,
                    padding: "2px 8px",
                    borderRadius: 9999,
                    fontSize: 10,
                    fontWeight: 600,
                    background:
                      invoice.status === "PAID" ? "#16A34A" : "#FFFBEB",
                    color: invoice.status === "PAID" ? "#fff" : "#B45309",
                    border: `1px solid ${
                      invoice.status === "PAID" ? "#16A34A" : "#FCD34D"
                    }`,
                  }}
                >
                  {invoice.status}
                </span>
              </div>
            </div>
            <p className="text-sm font-bold text-foreground mt-1">
              Total: ₹{Number(invoice.totalAmount).toLocaleString("en-IN")}
            </p>
          </CardHeader>
          <CardContent className="p-0">
            {payments.length === 0 ? (
              <div className="flex flex-col items-center gap-2 py-8">
                <IndianRupee className="h-6 w-6 text-muted-foreground/40" />
                <p className="text-xs text-muted-foreground">
                  No payment attempts yet
                </p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-muted border-b border-border text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
                      <th className="py-2 px-4">#</th>
                      <th className="py-2 px-4">Amount</th>
                      <th className="py-2 px-4">Method</th>
                      <th className="py-2 px-4">Status</th>
                      <th className="py-2 px-4">Date</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border text-xs">
                    {payments.map((p: any, i: number) => (
                      <tr key={p.id} className="hover:bg-secondary/20">
                        <td className="py-2.5 px-4 text-muted-foreground font-mono">
                          {i + 1}
                        </td>
                        <td className="py-2.5 px-4 font-bold">
                          ₹{Number(p.amount).toLocaleString("en-IN")}
                        </td>
                        <td className="py-2.5 px-4 text-muted-foreground">
                          {p.method}
                        </td>
                        <td className="py-2.5 px-4">
                          <PayStatusPill status={p.status} />
                        </td>
                        <td className="py-2.5 px-4 text-muted-foreground whitespace-nowrap">
                          {new Date(p.paidAt ?? p.createdAt).toLocaleDateString(
                            "en-IN",
                            {
                              day: "2-digit",
                              month: "short",
                              year: "numeric",
                            }
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Documents */}
      <Card className="border-border bg-card shadow-sm">
        <CardHeader className="border-b border-border py-3 px-5">
          <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
            Attached Documents
          </p>
        </CardHeader>
        <CardContent className="p-5">
          {docs.length > 0 ? (
            <div className="flex flex-col gap-1.5">
              {docs.map((doc) => (
                <div
                  key={doc.id}
                  className="flex items-center justify-between gap-4 rounded-md border border-border bg-muted/30 px-3 py-2"
                >
                  <div className="flex items-center gap-2 min-w-0">
                    <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                    <span className="text-xs font-medium text-foreground truncate max-w-xs">
                      {doc.serviceDocument?.name ?? doc.fileName}
                    </span>
                    {doc.fileSizeKb && (
                      <span className="text-[10px] text-muted-foreground shrink-0">
                        {doc.fileSizeKb} KB
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Badge
                      variant="outline"
                      className={`text-[10px] ${
                        DOC_STATUS_STYLES[doc.status] ??
                        "bg-muted text-muted-foreground"
                      }`}
                    >
                      {doc.status}
                    </Badge>
                    <a
                      href={doc.fileUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1 text-[10px] text-blue-600 hover:underline"
                    >
                      View <ExternalLink className="h-3 w-3" />
                    </a>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-xs text-muted-foreground">
              No documents attached.
            </p>
          )}
        </CardContent>
      </Card>

      {canDecide && (
        <div className="flex justify-end gap-2">
          <Button
            variant="destructive"
            onClick={() => setDecidingDecision("REJECTED")}
            className="gap-1.5"
          >
            <XCircle className="h-4 w-4" />
            Reject
          </Button>
          <Button
            onClick={() => setDecidingDecision("APPROVED")}
            className="gap-1.5"
          >
            <CheckCircle2 className="h-4 w-4" />
            Approve
          </Button>
        </div>
      )}

      {decidingDecision && (
        <ClientDecideDialog
          taskId={task.id}
          decision={decidingDecision}
          open={!!decidingDecision}
          onClose={() => setDecidingDecision(null)}
        />
      )}
    </div>
  );
}
