"use client";

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

interface DiscrepancyCardProps {
  discrepancy: Discrepancy;
  canResolve: boolean;
  onResolve: (discrepancy: Discrepancy) => void;
  onReopen: (discrepancy: Discrepancy) => void;
  /** Path prefix for shipment / PO links — use admin or supplier path here. */
  shipmentLinkPath?: (shipmentId: number) => string;
  purchaseOrderLinkPath?: (poId: number) => string;
  /** Hide the shipment header link when card is rendered inside a shipment detail view. */
  hideShipmentLink?: boolean;
  /** When true, the card starts collapsed (header-only) and expands on click. */
  defaultCollapsed?: boolean;
}

/**
 * Stored URLs are Drive viewer pages or download URLs — neither serves raw
 * image bytes for an <img> tag. Extract the file id and build a thumbnail URL.
 */
const extractDriveFileId = (url: string): string | null => {
  if (!url) return null;
  // Match `/file/d/{ID}` or `?id={ID}` patterns; else assume the input is already an id
  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];
  // Treat raw alphanumeric strings as a file id directly
  if (/^[a-zA-Z0-9_-]{20,}$/.test(url)) return url;
  return null;
};

const driveThumbnailUrl = (url: string, width = 400): 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: PalletReceivedCondition) => {
  if (cond === PalletReceivedCondition.DAMAGED) {
    return {
      label: "Damaged",
      badgeClass: "bg-amber-100 text-amber-800",
      icon: MdReportProblem,
      iconColor: "#B45309",
    };
  }
  if (cond === PalletReceivedCondition.MISSING) {
    return {
      label: "Missing",
      badgeClass: "bg-red-100 text-red-800",
      icon: MdRemoveCircleOutline,
      iconColor: "#B91C1C",
    };
  }
  return {
    label: cond,
    badgeClass: "bg-gray-200 text-gray-700",
    icon: MdReportProblem,
    iconColor: "#6B7280",
  };
};

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

const DiscrepancyCard: React.FC<DiscrepancyCardProps> = ({
  discrepancy,
  canResolve,
  onResolve,
  onReopen,
  shipmentLinkPath,
  purchaseOrderLinkPath,
  hideShipmentLink = false,
  defaultCollapsed = false,
}) => {
  const styles = conditionStyles(discrepancy.receivedCondition);
  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">
          <div className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-semibold">
            Pallet #{discrepancy.palletNumber}
          </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.conditionReportedAt && (
            <div className="text-xs text-gray-500">
              {formatDateTime(discrepancy.conditionReportedAt)}
            </div>
          )}
        </div>

        <div className="flex items-center gap-3">
          {!hideShipmentLink && discrepancy.shipmentNumber && 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">
        {/* Reported / Pallet info row */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
          <div>
            <div className="text-xs font-medium text-gray-400">
              Pallet barcode
            </div>
            <div className="text-gray-800">
              {discrepancy.palletBarcode || "—"}
            </div>
          </div>
          <div>
            <div className="text-xs font-medium text-gray-400">Reported by</div>
            <div className="text-gray-800">
              {userLabel(discrepancy.conditionReportedBy)}
            </div>
          </div>
          <div>
            <div className="text-xs font-medium text-gray-400">Reported at</div>
            <div className="text-gray-800">
              {discrepancy.conditionReportedAt
                ? formatDateTime(discrepancy.conditionReportedAt)
                : "—"}
            </div>
          </div>
        </div>

        {/* Description (damaged only) */}
        {discrepancy.receivedCondition === PalletReceivedCondition.DAMAGED &&
          discrepancy.conditionDescription && (
            <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.conditionDescription}
              </p>
            </div>
          )}

        {/* Photos */}
        {discrepancy.conditionImages?.length > 0 && (
          <div>
            <div className="text-xs font-medium text-gray-400 mb-2">
              Photos ({discrepancy.conditionImages.length})
            </div>
            <div className="flex flex-wrap gap-2">
              {discrepancy.conditionImages.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"
                  title={`Open photo ${idx + 1} in new tab`}
                >
                  <img
                    src={driveThumbnailUrl(url, 200)}
                    alt={`Damage photo ${idx + 1}`}
                    referrerPolicy="no-referrer"
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      // Hide the broken image so the click target still works
                      (e.currentTarget as HTMLImageElement).style.display =
                        "none";
                    }}
                  />
                </a>
              ))}
            </div>
          </div>
        )}

        {/* Affected items */}
        {discrepancy.affectedItems.length > 0 && (
          <div>
            <div className="text-xs font-medium text-gray-400 mb-2">
              Affected items
            </div>
            <div className="rounded-md border border-gray-200 overflow-hidden">
              <table className="min-w-full divide-y divide-gray-200 text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left text-xs font-bold text-black uppercase tracking-wider">
                      Product
                    </th>
                    <th className="px-3 py-2 text-left text-xs font-bold text-black uppercase tracking-wider">
                      PO #
                    </th>
                    <th className="px-3 py-2 text-left text-xs font-bold text-black uppercase tracking-wider">
                      Supplier
                    </th>
                    <th className="px-3 py-2 text-right text-xs font-bold text-black uppercase tracking-wider">
                      Qty
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-100">
                  {discrepancy.affectedItems.map((item, idx) => (
                    <tr
                      key={`${item.purchaseOrderId}-${item.productId}-${idx}`}
                      className={idx % 2 === 0 ? "bg-white" : "bg-[#F2F9FF]"}
                    >
                      <td className="px-3 py-2 text-gray-800">
                        {item.productName}
                      </td>
                      <td className="px-3 py-2 text-gray-700">
                        {purchaseOrderLinkPath ? (
                          <Link
                            href={purchaseOrderLinkPath(item.purchaseOrderId)}
                            className="text-[#3997E0] hover:underline"
                          >
                            {item.purchaseOrderNumber}
                          </Link>
                        ) : (
                          item.purchaseOrderNumber
                        )}
                      </td>
                      <td className="px-3 py-2 text-gray-700">
                        {item.supplierName || "—"}
                      </td>
                      <td className="px-3 py-2 text-right text-gray-800 font-medium">
                        × {item.quantity}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Resolution block */}
        {isResolved && (
          <div className="bg-green-50 border border-green-100 rounded-md p-3 text-sm">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 mb-1">
              <div className="text-xs font-medium text-green-700">
                Resolved by{" "}
                <span className="font-semibold">
                  {userLabel(discrepancy.discrepancyResolvedBy)}
                </span>
                {discrepancy.discrepancyResolvedAt && (
                  <>
                    {" · "}
                    {formatDateTime(discrepancy.discrepancyResolvedAt)}
                  </>
                )}
              </div>
            </div>
            {discrepancy.discrepancyResolutionNote && (
              <p className="text-gray-800 whitespace-pre-wrap">
                {discrepancy.discrepancyResolutionNote}
              </p>
            )}
          </div>
        )}
      </div>

      {/* Footer / Actions */}
      {canResolve && (
        <div className="px-6 py-3 bg-gray-50 border-t border-gray-100 flex justify-end">
          {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 DiscrepancyCard;
