"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  MdReportProblem,
  MdRemoveCircleOutline,
  MdCheckCircle,
  MdRestore,
  MdOpenInNew,
  MdExpandMore,
  MdExpandLess,
  MdUndo,
} from "react-icons/md";
import {
  ItemDiscrepancy,
  ShipmentPalletItemCondition,
} from "@/types/item-discrepancy";
import { formatDateTime } from "@/utils/dateUtils";

interface ItemDiscrepancyCardProps {
  discrepancy: ItemDiscrepancy;
  canResolve: boolean;
  onResolve: (d: ItemDiscrepancy) => void;
  onReopen: (d: ItemDiscrepancy) => void;
  /** Available to admin: revert the item back to OK and restore stock. Hidden when resolved. */
  onClear?: (d: ItemDiscrepancy) => void;
  shipmentLinkPath?: (shipmentId: number) => string;
  purchaseOrderLinkPath?: (poId: number) => string;
  hideShipmentLink?: boolean;
  defaultCollapsed?: boolean;
}

// Drive thumbnail / viewer URL helpers — same pattern as DiscrepancyCard.
const extractDriveFileId = (url: string): string | null => {
  if (!url) return null;
  const fileMatch = url.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
  if (fileMatch) return fileMatch[1];
  const idMatch = url.match(/[?&]id=([a-zA-Z0-9_-]+)/);
  if (idMatch) return idMatch[1];
  if (/^[a-zA-Z0-9_-]{20,}$/.test(url)) return url;
  return null;
};

const driveThumbnailUrl = (url: string, width = 200): string => {
  const id = extractDriveFileId(url);
  return id
    ? `https://drive.google.com/thumbnail?id=${id}&sz=w${width}`
    : url;
};

const driveViewerUrl = (url: string): string => {
  const id = extractDriveFileId(url);
  return id ? `https://drive.google.com/file/d/${id}/view` : url;
};

const conditionStyles = (cond: ShipmentPalletItemCondition) => {
  if (cond === ShipmentPalletItemCondition.DAMAGED) {
    return {
      label: "Damaged",
      badgeClass: "bg-amber-100 text-amber-800",
      icon: MdReportProblem,
      iconColor: "#B45309",
    };
  }
  if (cond === ShipmentPalletItemCondition.MISSING) {
    return {
      label: "Missing",
      badgeClass: "bg-red-100 text-red-800",
      icon: MdRemoveCircleOutline,
      iconColor: "#B91C1C",
    };
  }
  return {
    label: "OK",
    badgeClass: "bg-green-100 text-green-800",
    icon: MdCheckCircle,
    iconColor: "#15803D",
  };
};

const userLabel = (
  u: ItemDiscrepancy["itemConditionReportedBy"] | ItemDiscrepancy["itemDiscrepancyResolvedBy"]
) => {
  if (!u) return "Unknown";
  const name = `${u.firstname ?? ""} ${u.lastname ?? ""}`.trim();
  return name || u.email || "Unknown";
};

const ItemDiscrepancyCard: React.FC<ItemDiscrepancyCardProps> = ({
  discrepancy,
  canResolve,
  onResolve,
  onReopen,
  onClear,
  shipmentLinkPath,
  purchaseOrderLinkPath,
  hideShipmentLink = false,
  defaultCollapsed = false,
}) => {
  const styles = conditionStyles(discrepancy.itemCondition);
  const Icon = styles.icon;
  const isResolved = discrepancy.isResolved;
  const [isExpanded, setIsExpanded] = useState(!defaultCollapsed);

  return (
    <div className="bg-white rounded-lg shadow-[0px_4px_34px_0px_rgba(0,59,113,0.16)] border border-gray-100 overflow-hidden">
      {/* Header */}
      <div
        className={`px-6 py-4 border-b border-gray-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 ${
          defaultCollapsed ? "cursor-pointer hover:bg-gray-50 transition-colors" : ""
        }`}
        onClick={() => {
          if (defaultCollapsed) setIsExpanded((e) => !e);
        }}
      >
        <div className="flex items-center flex-wrap gap-3">
          {discrepancy.palletNumber !== null && (
            <div className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-semibold">
              Pallet #{discrepancy.palletNumber}
            </div>
          )}
          <div className="text-sm font-semibold text-gray-800">
            {discrepancy.productName}
          </div>
          <div
            className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold ${styles.badgeClass}`}
          >
            <Icon size={14} color={styles.iconColor} />
            {styles.label}
          </div>
          {isResolved ? (
            <div className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">
              <MdCheckCircle size={14} color="#15803D" />
              Resolved
            </div>
          ) : (
            <div className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-700">
              Active
            </div>
          )}
          {discrepancy.itemConditionReportedAt && (
            <div className="text-xs text-gray-500">
              {formatDateTime(discrepancy.itemConditionReportedAt)}
            </div>
          )}
        </div>

        <div className="flex items-center gap-3">
          {!hideShipmentLink &&
            discrepancy.shipmentNumber &&
            discrepancy.shipmentId !== null &&
            shipmentLinkPath && (
              <Link
                href={shipmentLinkPath(discrepancy.shipmentId)}
                onClick={(e) => e.stopPropagation()}
                className="inline-flex items-center gap-1 text-sm text-[#3997E0] hover:underline"
              >
                {discrepancy.shipmentNumber}
                <MdOpenInNew size={14} />
              </Link>
            )}
          {defaultCollapsed && (
            <button
              type="button"
              className="text-gray-500 hover:text-gray-700"
              onClick={(e) => {
                e.stopPropagation();
                setIsExpanded((s) => !s);
              }}
              aria-label={isExpanded ? "Collapse" : "Expand"}
            >
              {isExpanded ? (
                <MdExpandLess size={20} />
              ) : (
                <MdExpandMore size={20} />
              )}
            </button>
          )}
        </div>
      </div>

      {!isExpanded ? null : (
        <>
          {/* Body */}
          <div className="px-6 py-4 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
              <div>
                <div className="text-xs font-medium text-gray-400">Barcode</div>
                <div className="text-gray-800">{discrepancy.barcode || "—"}</div>
              </div>
              <div>
                <div className="text-xs font-medium text-gray-400">PO #</div>
                <div className="text-gray-800">
                  {purchaseOrderLinkPath && discrepancy.purchaseOrderId ? (
                    <Link
                      href={purchaseOrderLinkPath(discrepancy.purchaseOrderId)}
                      className="text-[#3997E0] hover:underline"
                    >
                      {discrepancy.purchaseOrderNumber}
                    </Link>
                  ) : (
                    discrepancy.purchaseOrderNumber || "—"
                  )}
                </div>
              </div>
              <div>
                <div className="text-xs font-medium text-gray-400">Supplier</div>
                <div className="text-gray-800">
                  {discrepancy.supplierName || "—"}
                </div>
              </div>
              <div>
                <div className="text-xs font-medium text-gray-400">
                  Reported by
                </div>
                <div className="text-gray-800">
                  {userLabel(discrepancy.itemConditionReportedBy)}
                </div>
              </div>
              <div>
                <div className="text-xs font-medium text-gray-400">
                  Reported at
                </div>
                <div className="text-gray-800">
                  {discrepancy.itemConditionReportedAt
                    ? formatDateTime(discrepancy.itemConditionReportedAt)
                    : "—"}
                </div>
              </div>
            </div>

            {discrepancy.itemCondition ===
              ShipmentPalletItemCondition.DAMAGED &&
              discrepancy.itemConditionDescription && (
                <div>
                  <div className="text-xs font-medium text-gray-400 mb-1">
                    Description
                  </div>
                  <p className="text-sm text-gray-800 whitespace-pre-wrap bg-amber-50 border border-amber-100 rounded-md p-3">
                    {discrepancy.itemConditionDescription}
                  </p>
                </div>
              )}

            {discrepancy.itemConditionImages.length > 0 && (
              <div>
                <div className="text-xs font-medium text-gray-400 mb-2">
                  Photos ({discrepancy.itemConditionImages.length})
                </div>
                <div className="flex flex-wrap gap-2">
                  {discrepancy.itemConditionImages.map((url, idx) => (
                    <a
                      key={idx}
                      href={driveViewerUrl(url)}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="block w-24 h-24 rounded-md overflow-hidden border border-gray-200 hover:opacity-90 transition-opacity bg-gray-50"
                    >
                      <img
                        src={driveThumbnailUrl(url, 200)}
                        alt={`Damage photo ${idx + 1}`}
                        referrerPolicy="no-referrer"
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          (e.currentTarget as HTMLImageElement).style.display =
                            "none";
                        }}
                      />
                    </a>
                  ))}
                </div>
              </div>
            )}

            {isResolved && (
              <div className="bg-green-50 border border-green-100 rounded-md p-3 text-sm">
                <div className="text-xs font-medium text-green-700 mb-1">
                  Resolved by{" "}
                  <span className="font-semibold">
                    {userLabel(discrepancy.itemDiscrepancyResolvedBy)}
                  </span>
                  {discrepancy.itemDiscrepancyResolvedAt && (
                    <>
                      {" · "}
                      {formatDateTime(discrepancy.itemDiscrepancyResolvedAt)}
                    </>
                  )}
                </div>
                {discrepancy.itemDiscrepancyResolutionNote && (
                  <p className="text-gray-800 whitespace-pre-wrap">
                    {discrepancy.itemDiscrepancyResolutionNote}
                  </p>
                )}
              </div>
            )}
          </div>

          {/* Footer */}
          {(canResolve || (!isResolved && onClear)) && (
            <div className="px-6 py-3 bg-gray-50 border-t border-gray-100 flex justify-end gap-2">
              {!isResolved && onClear && (
                <button
                  onClick={() => onClear(discrepancy)}
                  className="inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-md border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors"
                  title="Item is fine — restore stock and remove the flag"
                >
                  <MdUndo size={16} />
                  Mark OK
                </button>
              )}
              {canResolve && (
                isResolved ? (
                  <button
                    onClick={() => onReopen(discrepancy)}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-md border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors"
                  >
                    <MdRestore size={16} />
                    Reopen
                  </button>
                ) : (
                  <button
                    onClick={() => onResolve(discrepancy)}
                    className="inline-flex items-center gap-1 px-4 py-1.5 text-sm rounded-md bg-[#3997E0] text-white hover:bg-blue-600 transition-colors"
                  >
                    <MdCheckCircle size={16} />
                    Mark Resolved
                  </button>
                )
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default ItemDiscrepancyCard;
