"use client";

import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
  ArrowLeft,
  CalendarClock,
  Flag,
  FileText,
  Eye,
  Users2,
  CheckCircle2,
  XCircle,
  Clock,
  User,
  IndianRupee,
  RefreshCw,
  Copy,
  Check,
} from "lucide-react";
import { useAdminGetTask } from "../hooks/task.hooks";
import { useAdminGetInvoice } from "../../payment/hooks/payment.hook";
import { useRouter } from "next/navigation";
import { getStatusVariant } from "@/lib/status-variant";
import { formatDate, formatDateTime } from "@/lib/format-date";
import { useTaskSocket } from "@/hooks/useTaskSocket";
import { useAppSelector } from "@/lib/store";

function formatFileSize(kb?: number | null) {
  if (!kb) return "";
  return kb < 1024 ? `${kb} KB` : `${(kb / 1024).toFixed(1)} MB`;
}

function isImage(fileName: string) {
  return /\.(png|jpe?g|gif|webp|svg)$/i.test(fileName);
}

function fileExt(fileName: string) {
  return fileName.split(".").pop()?.toUpperCase() ?? "FILE";
}

const PAY_STATUS: Record<
  string,
  {
    label: string;
    color: string;
    bg: string;
    border: string;
    icon: React.ReactNode;
  }
> = {
  SUCCESS: {
    label: "Success",
    color: "#FFFFFF",
    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} />,
  },
};

const INV_STATUS: Record<
  string,
  { color: string; bg: string; border: string }
> = {
  PAID: { color: "#FFFFFF", bg: "#16A34A", border: "#16A34A" },
  SENT: { color: "#B45309", bg: "#FFFBEB", border: "#FCD34D" },
  DRAFT: { color: "#6B7280", bg: "#F3F4F6", border: "#D1D5DB" },
  OVERDUE: { color: "#DC2626", bg: "#FEF2F2", border: "#FCA5A5" },
  CANCELLED: { color: "#6B7280", bg: "#F3F4F6", border: "#D1D5DB" },
  PARTIALLY_PAID: { color: "#2563EB", bg: "#EFF6FF", border: "#93C5FD" },
};

function StatusPill({
  label,
  color,
  bg,
  border,
  icon,
}: {
  label: string;
  color: string;
  bg: string;
  border: string;
  icon?: React.ReactNode;
}) {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        padding: "3px 9px",
        borderRadius: 9999,
        border: `1px solid ${border}`,
        background: bg,
        color,
        fontSize: 10,
        fontWeight: 600,
        whiteSpace: "nowrap",
      }}
    >
      {icon}
      {label}
    </span>
  );
}

function PayStatusBadge({ status }: { status: string }) {
  const cfg = PAY_STATUS[status];
  return (
    <StatusPill
      label={cfg?.label ?? status}
      color={cfg?.color ?? "#374151"}
      bg={cfg?.bg ?? "#F3F4F6"}
      border={cfg?.border ?? "#D1D5DB"}
      icon={cfg?.icon}
    />
  );
}

function InvStatusBadge({ status }: { status: string }) {
  const cfg = INV_STATUS[status];
  return (
    <StatusPill
      label={status.replace(/_/g, " ")}
      color={cfg?.color ?? "#374151"}
      bg={cfg?.bg ?? "#F3F4F6"}
      border={cfg?.border ?? "#D1D5DB"}
    />
  );
}

function CopyText({ value }: { value: string }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(value);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
      <span
        style={{
          fontFamily: "monospace",
          fontSize: 10,
          color: "hsl(var(--muted-foreground))",
        }}
      >
        {value}
      </span>
      <button
        onClick={copy}
        style={{
          background: "none",
          border: "none",
          cursor: "pointer",
          padding: 2,
          borderRadius: 4,
          color: copied ? "#16A34A" : "hsl(var(--muted-foreground))",
          display: "flex",
          alignItems: "center",
        }}
      >
        {copied ? <Check size={10} /> : <Copy size={10} />}
      </button>
    </span>
  );
}

function ApprovalIcon({ status }: { status: string }) {
  if (status === "APPROVED")
    return <CheckCircle2 className="w-4 h-4 text-emerald-500" />;
  if (status === "REJECTED")
    return <XCircle className="w-4 h-4 text-red-500" />;
  return <Clock className="w-4 h-4 text-amber-500" />;
}

const InfoRow = ({ label, value }: { label: string; value: string }) => (
  <div className="flex items-center gap-8 py-2.5 border-none">
    <span className="text-xs font-medium text-muted-foreground shrink-0">
      {label}:
    </span>

    <span className="text-sm font-medium text-foreground truncate">
      {value || "-"}
    </span>
  </div>
);
export function ViewTask({ taskId }: { taskId: string }) {
  const router = useRouter();
  const orgId = useAppSelector((s) => s.auth.user?.organizationId);
  useTaskSocket(orgId, ["admin-tasks"]);
  const { data: task, isLoading } = useAdminGetTask(taskId);
  const { data: invoice } = useAdminGetInvoice(task?.invoice?.id);

  if (isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-10 w-64" />
        <Skeleton className="h-24 w-full rounded-xl" />
        <div className="grid grid-cols-3 gap-4">
          <Skeleton className="h-64 rounded-xl" />
          <Skeleton className="h-64 rounded-xl col-span-2" />
        </div>
      </div>
    );
  }

  if (!task)
    return <p className="text-muted-foreground text-sm">Task not found.</p>;

  const documents = task.documents ?? [];
  const approvals = task.approvals ?? [];

  return (
    <div className="space-y-5 w-full">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <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>
      </div>
      <div>
        <h2 className="text-xl font-bold tracking-tight">Task Details</h2>
        <p className="text-muted-foreground text-sm">
          {task.client.name} · {task.service.name}
        </p>
      </div>

      {/* Summary bar */}
      <Card className="p-4">
        <div className="flex flex-col sm:flex-row sm:items-center gap-4">
          <div className="flex items-center gap-3 flex-1 min-w-0">
            <div className="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center shrink-0">
              <span className="text-sm font-bold text-primary">
                {task.title.trim().slice(0, 2).toUpperCase()}
              </span>
            </div>
            <div className="min-w-0">
              <p className="font-semibold text-sm truncate">{task.title}</p>
              <p className="text-xs text-muted-foreground">
                {task.service.name} · {task.service.category}
              </p>
            </div>
          </div>
          <div className="flex flex-wrap items-center gap-2 shrink-0">
            <Badge
              variant={getStatusVariant(task.status)}
              className="text-[11px] px-2.5 py-0.5"
            >
              {task.status.replace(/_/g, " ")}
            </Badge>
            <Badge
              variant={getStatusVariant(task.priority)}
              className="text-[11px] px-2.5 py-0.5 gap-1"
            >
              {task.priority}
            </Badge>
            {task.dueDate && (
              <span className="flex items-center gap-1 text-xs text-muted-foreground border border-border rounded-full px-2.5 py-0.5">
                <CalendarClock className="h-3 w-3" />
                {formatDate(task.dueDate)}
              </span>
            )}
          </div>
        </div>
      </Card>

      {/* Main layout */}
      <div className="grid grid-cols-1  xl:grid-cols-12 gap-5">
        {/* LEFT col — Task Info + Client (row) + Assigned To */}
        <div className="xl:col-span-4 flex flex-col gap-4">
          {/* Task Info + Client side by side */}
          <div className="grid grid-cols-2 gap-4">
            {/* Task Info */}
            <Card className="p-4">
              <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wide mb-3">
                Task Info
              </p>
              <div className="divide-y divide-border">
                <InfoRow label="Service" value={task.service.name} />
                <InfoRow label="Category" value={task.service.category} />
                {task.department && (
                  <InfoRow label="Department" value={task.department.name} />
                )}
                <InfoRow
                  label="Created"
                  value={formatDateTime(task.createdAt)}
                />
              </div>
            </Card>

            {/* Client */}
            <Card className="p-4">
              <div className="flex items-center gap-1.5 mb-3">
                <Users2 className="h-3.5 w-3.5 text-primary shrink-0" />
                <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wide">
                  Client
                </p>
              </div>
              <div className="divide-y divide-border">
                <InfoRow label="Name" value={task.client.name} />
                <InfoRow label="Email" value={task.client.email} />
                {task.client.companyName && (
                  <InfoRow label="Company" value={task.client.companyName} />
                )}
              </div>
            </Card>
          </div>

          {/* Assigned To */}
          <Card className="p-4">
            <div className="flex items-center gap-1.5 mb-3">
              <User className="h-3.5 w-3.5 text-primary shrink-0" />
              <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wide">
                Assigned To
              </p>
            </div>

            {task.assignedEmployee ? (
              <div className="flex items-center gap-6 w-full">
                <div className="flex items-center gap-2 flex-1 min-w-0">
                  <span className="text-[10px] font-semibold uppercase text-muted-foreground shrink-0">
                    Email:
                  </span>
                  <span className="text-sm truncate">
                    {task.assignedEmployee.email}
                  </span>
                </div>

                <div className="flex items-center gap-2 flex-1 min-w-0">
                  <span className="text-[10px] font-semibold uppercase text-muted-foreground shrink-0">
                    Role:
                  </span>
                  <span className="text-sm capitalize truncate">
                    {task.assignedEmployee.role.toLowerCase()}
                  </span>
                </div>

                <div className="flex items-center gap-2 flex-1 min-w-0">
                  <span className="text-[10px] font-semibold uppercase text-muted-foreground shrink-0">
                    Name:
                  </span>
                  <span className="text-sm truncate">
                    {task.assignedEmployee.name}
                  </span>
                </div>
              </div>
            ) : (
              <p className="text-xs text-muted-foreground">Not assigned</p>
            )}
          </Card>
        </div>

        {/* RIGHT — Description + Documents + Approvals */}
        <div className="xl:col-span-8 flex flex-col gap-4">
          {/* Description */}
          {task.description && (
            <Card className="p-6">
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-3">
                Description
              </p>
              <p className="text-sm whitespace-pre-wrap leading-relaxed text-muted-foreground">
                {task.description}
              </p>
            </Card>
          )}

          {/* Documents */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5">
                <FileText className="h-3.5 w-3.5 text-primary" /> Documents
              </p>
              {documents.length > 0 && (
                <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
                  {documents.length}
                </span>
              )}
            </div>

            {documents.length === 0 ? (
              <div className="flex flex-col items-center gap-2 rounded-xl border border-dashed p-10 text-center">
                <FileText className="w-8 h-8 text-muted-foreground/30" />
                <p className="text-sm text-muted-foreground">
                  No documents uploaded
                </p>
              </div>
            ) : (
              <div className="space-y-2">
                {documents.map((doc) => (
                  <div
                    key={doc.id}
                    className="flex items-center justify-between rounded-lg border border-border px-3 py-2.5 hover:bg-muted/40 transition-colors"
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      {isImage(doc.fileName) ? (
                        <div className="w-9 h-9 rounded-md overflow-hidden shrink-0 border border-border">
                          <img
                            src={doc.fileUrl}
                            alt={doc.fileName}
                            className="w-full h-full object-cover"
                          />
                        </div>
                      ) : (
                        <div className="w-9 h-9 rounded-md bg-primary/10 flex items-center justify-center shrink-0">
                          <span className="text-[10px] font-bold text-primary">
                            {fileExt(doc.fileName)}
                          </span>
                        </div>
                      )}
                      <div className="min-w-0">
                        <p className="text-sm font-medium truncate">
                          {doc.fileName}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {formatFileSize(doc.fileSizeKb)}
                          {(doc as any).serviceDocument?.name &&
                            ` · ${(doc as any).serviceDocument.name}`}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-1.5 shrink-0 ml-3">
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-7 w-7"
                        asChild
                      >
                        <a
                          href={doc.fileUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          <Eye className="h-3.5 w-3.5" />
                        </a>
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>

          {/* Approvals */}
          {approvals.length > 0 && (
            <Card className="p-6">
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-3">
                Approvals
              </p>
              <div className="space-y-2">
                {approvals.map((a) => (
                  <div
                    key={a.id}
                    className="flex items-center justify-between rounded-lg border px-4 py-3 bg-muted/20"
                  >
                    <div className="flex items-center gap-2.5">
                      <ApprovalIcon status={a.status} />
                      <span className="text-sm font-medium">
                        {a.stage.replace(/_/g, " ")}
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      {a.remarks && (
                        <span className="text-xs text-muted-foreground truncate max-w-[120px]">
                          {a.remarks}
                        </span>
                      )}
                      <Badge
                        variant={getStatusVariant(a.status)}
                        className="text-[10px]"
                      >
                        {a.status}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          )}

          {/* Invoice & Payment */}
          {invoice && (
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5">
                  <IndianRupee className="h-3.5 w-3.5 text-primary" /> Invoice &
                  Payment
                </p>
                <InvStatusBadge status={invoice.status} />
              </div>

              {/* Invoice summary */}
              <div className="rounded-lg border border-border bg-muted/20 p-4 mb-4 space-y-1.5">
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">Invoice No.</span>
                  <span className="font-medium font-mono">
                    {invoice.invoiceNumber}
                  </span>
                </div>
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">Subtotal</span>
                  <span>
                    ₹{Number(invoice.subtotal).toLocaleString("en-IN")}
                  </span>
                </div>
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">GST</span>
                  <span>
                    ₹{Number(invoice.gstAmount).toLocaleString("en-IN")}
                  </span>
                </div>
                <div className="flex justify-between text-xs font-bold border-t border-border pt-1.5 mt-1.5">
                  <span>Total</span>
                  <span className="text-primary">
                    ₹{Number(invoice.totalAmount).toLocaleString("en-IN")}
                  </span>
                </div>
                {invoice.dueDate && (
                  <div className="flex justify-between text-xs">
                    <span className="text-muted-foreground">Due Date</span>
                    <span>{formatDate(invoice.dueDate)}</span>
                  </div>
                )}
              </div>

              {/* Payment Transactions */}
              {invoice.payments.length > 0 ? (
                <div className="space-y-2">
                  <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wide mb-3">
                    Payment Transactions
                  </p>
                  {invoice.payments.map((p) => (
                    <div
                      key={p.id}
                      className="rounded-lg border border-border bg-muted/10 px-4 py-3"
                    >
                      <div className="flex items-center justify-between gap-4">
                        {/* Left: status + method */}
                        <div className="flex items-center gap-2.5">
                          <PayStatusBadge status={p.status} />
                          <span className="text-xs text-muted-foreground font-medium">
                            {p.method}
                          </span>
                        </div>
                        {/* Right: amount + date */}
                        <div className="text-right shrink-0">
                          <p className="text-sm font-bold">
                            ₹{Number(p.amount).toLocaleString("en-IN")}
                          </p>
                          <p className="text-[10px] text-muted-foreground">
                            {p.paidAt
                              ? formatDateTime(p.paidAt)
                              : formatDateTime(p.createdAt)}
                          </p>
                        </div>
                      </div>
                      {/* Ref below */}
                      {p.transactionRef && (
                        <div className="mt-2 pt-2 border-t border-border/50">
                          <CopyText value={p.transactionRef} />
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-xs text-muted-foreground text-center py-2">
                  No payment transactions yet
                </p>
              )}
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
