"use client";

import { CalendarPlus, ChevronDown, ExternalLink, MessageCircle, PhoneCall } from "lucide-react";

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import type { Customer } from "@/lib/order/types";

interface CustomerSectionProps {
  customer: Customer;
  menuGivenDates?: string[];
  onMarkMenuToday?: () => void;
  onViewLastOrder?: () => void;
}

export function CustomerSection({ customer, menuGivenDates, onMarkMenuToday, onViewLastOrder }: CustomerSectionProps) {
  const whatsappUrl = `https://wa.me/${customer.mo.replace(/\D/g, "")}`;
  const callUrl = `tel:${customer.mo}`;

  return (
    <Collapsible defaultOpen>
      {/* Customer name is the section header — matches wireframe */}
      <CollapsibleTrigger className="flex w-full items-center justify-between border-b border-blue-200/70 bg-blue-100 px-3 py-1.5 text-left dark:border-blue-900/40 dark:bg-blue-950/40">
        <span className="font-semibold text-sm text-blue-900 dark:text-blue-100">{customer.na}</span>
        <ChevronDown className="size-3.5 text-blue-500 transition-transform [[data-state=open]_&]:rotate-180" />
      </CollapsibleTrigger>
      <CollapsibleContent>
        <div className="space-y-1 px-3 py-2 text-sm">

          {/* Mobile: number itself is tel: link + WhatsApp icon */}
          <div className="flex gap-2">
            <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">mo:</span>
            <div className="flex items-center gap-2">
              <a href={callUrl} className="font-mono text-[13px] hover:text-primary hover:underline" title="Call">
                {customer.mo}
              </a>
              <a
                href={whatsappUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="rounded p-0.5 text-muted-foreground transition-colors hover:text-green-600"
                title="WhatsApp"
              >
                <MessageCircle className="size-3.5" />
              </a>
            </div>
          </div>

          {customer.ph && (
            <div className="flex gap-2">
              <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">ph:</span>
              <div className="flex items-center gap-2">
                <span className="font-mono text-[13px]">{customer.ph}</span>
                <a href={`tel:${customer.ph}`} className="rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground" title="Call landline">
                  <PhoneCall className="size-3.5" />
                </a>
              </div>
            </div>
          )}
          {customer.em && <FieldRow label="em" value={customer.em} />}
          {customer.pn && <FieldRow label="pn" value={customer.pn} mono />}
          {customer.cn && (
            <FieldRow label="cn" value={customer.cn} valueClassName="text-amber-700 dark:text-amber-400" />
          )}

          {/* History sub-section */}
          <div className="mt-2 border-t pt-2">
            <Collapsible>
              <CollapsibleTrigger className="flex w-full items-center gap-1 text-left">
                <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">life:</span>
                <span className="text-[13px]">
                  £{customer.lifetimeSpend.toFixed(2)}{" "}
                  <span className="text-muted-foreground">({customer.lifetimeOrders} orders)</span>
                </span>
                <span className="ml-auto text-muted-foreground text-xs">˄˅</span>
              </CollapsibleTrigger>
              <CollapsibleContent>
                  <div className="pl-12 pt-1 space-y-1">
                  {customer.lastOrderAmount !== undefined && customer.lastOrderAt && (
                    <div className="flex gap-2">
                      <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">last:</span>
                      <button
                        type="button"
                        onClick={onViewLastOrder}
                        className="flex items-center gap-1 text-[13px] text-primary hover:underline"
                        title="View previous order"
                      >
                        £{customer.lastOrderAmount.toFixed(2)}
                        {" · "}
                        {new Date(customer.lastOrderAt).toLocaleDateString("en-GB", {
                          day: "2-digit", month: "short", year: "numeric",
                        })}
                        <ExternalLink className="size-3 opacity-50" />
                      </button>
                    </div>
                  )}
                  {/* Menu given dates + click-to-mark-today */}
                  <div className="flex gap-2 items-start">
                    <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground leading-tight pt-0.5">
                      Menu<br/>given:
                    </span>
                    <div className="flex flex-col gap-0.5">
                      {menuGivenDates && menuGivenDates.length > 0 ? (
                        <span className="text-[13px] text-muted-foreground">
                          {menuGivenDates.slice(0, 2).map((d) =>
                            new Date(d).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })
                          ).join("  ·  ")}
                        </span>
                      ) : (
                        <span className="text-[12px] text-muted-foreground italic">not recorded</span>
                      )}
                      {onMarkMenuToday && (
                        <button
                          type="button"
                          onClick={onMarkMenuToday}
                          className="flex items-center gap-1 text-[11px] text-primary hover:underline w-fit"
                          title="Mark today as menu given"
                        >
                          <CalendarPlus className="size-3" />
                          Mark today
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              </CollapsibleContent>
            </Collapsible>
          </div>
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}

function FieldRow({
  label,
  value,
  mono = false,
  valueClassName = "",
}: {
  label: string;
  value: string;
  mono?: boolean;
  valueClassName?: string;
}) {
  return (
    <div className="flex gap-2">
      <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">{label}:</span>
      <span className={`flex-1 text-[13px] ${mono ? "font-mono" : ""} ${valueClassName}`}>{value}</span>
    </div>
  );
}
