"use client";

import { useState } from "react";

import { Check, ChevronDown, MessageSquare, Pencil, X } from "lucide-react";

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { useT } from "@/lib/i18n";
import { SectionHeader } from "./section-header";

const QUICK_REPLIES: { code: string; label: string; text: string }[] = [
  { code: "/otw",  label: "On the way",        text: "Your order is on the way. Driver will arrive shortly." },
  { code: "/arr",  label: "Arrived",           text: "Our driver has arrived at your address. Please come to the door." },
  { code: "/call", label: "Will call on arrival", text: "Driver will call you when they arrive." },
  { code: "/del",  label: "Delivered",         text: "Your order has been delivered. Thank you for ordering with us!" },
  { code: "/anf",  label: "Address not found", text: "Our driver could not find the address. Please call us back on the number provided." },
  { code: "/dly",  label: "Delay",             text: "We apologise for the delay. Your order will be with you shortly." },
  { code: "/conf", label: "Order confirmed",   text: "Your order has been confirmed. We will start preparing it shortly." },
  { code: "/rdy",  label: "Ready for collection", text: "Your order is ready for collection. Please come to the counter." },
];

interface MessagesSectionProps {
  message?: string;
  readOnly?: boolean;
  onUpdate?: (message: string) => void;
}

export function MessagesSection({ message, readOnly = false, onUpdate }: MessagesSectionProps) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(message ?? "");
  const [showReplies, setShowReplies] = useState(false);
  const t = useT();

  const handleSave = () => {
    onUpdate?.(draft.trim());
    setEditing(false);
  };

  const handleCancel = () => {
    setDraft(message ?? "");
    setEditing(false);
  };

  return (
    <Collapsible defaultOpen={!!message}>
      <CollapsibleTrigger className="w-full">
        <SectionHeader icon={MessageSquare} label={t.sec_messages} />
      </CollapsibleTrigger>
      <CollapsibleContent>
        <div className="px-3 py-2">
          {editing ? (
            <div className="space-y-2">
              {/* Quick-reply picker */}
              <div>
                <button
                  type="button"
                  onClick={() => setShowReplies((v) => !v)}
                  className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary transition-colors"
                >
                  <ChevronDown className={`size-3 transition-transform ${showReplies ? "rotate-180" : ""}`} />
                  {t.msg_quick_replies}
                </button>
                {showReplies && (
                  <div className="mt-1 rounded border bg-muted/30 divide-y">
                    {QUICK_REPLIES.map((r) => (
                      <button
                        key={r.code}
                        type="button"
                        onClick={() => { setDraft(r.text); setShowReplies(false); }}
                        className="flex w-full items-center gap-2 px-2 py-1.5 text-left hover:bg-muted/60 transition-colors"
                      >
                        <span className="font-mono text-[10px] text-primary shrink-0 w-12">{r.code}</span>
                        <span className="text-[12px] text-muted-foreground">{r.label}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
              <textarea
                value={draft}
                onChange={(e) => setDraft(e.target.value)}
                placeholder={`${t.msg_placeholder} (${t.msg_quick_replies})`}
                rows={3}
                className="w-full rounded border px-2 py-1.5 text-[13px] leading-relaxed resize-none outline-none focus:border-primary focus:ring-1 focus:ring-primary/30"
              />
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleSave}
                  className="flex items-center gap-1 rounded bg-primary px-3 py-1 text-[12px] font-semibold text-primary-foreground hover:bg-primary/90"
                >
                  <Check className="size-3" /> {t.msg_save}
                </button>
                <button
                  type="button"
                  onClick={handleCancel}
                  className="flex items-center gap-1 rounded border px-3 py-1 text-[12px] text-muted-foreground hover:text-foreground"
                >
                  <X className="size-3" /> {t.msg_cancel}
                </button>
              </div>
            </div>
          ) : (
            <div className="flex items-start justify-between gap-2">
              <p className="flex-1 text-[13px] leading-relaxed">
                {message ? (
                  message
                ) : (
                  <span className="italic text-muted-foreground">{t.msg_no_message}</span>
                )}
              </p>
              {!readOnly && onUpdate && (
                <button
                  type="button"
                  onClick={() => { setDraft(message ?? ""); setEditing(true); }}
                  className="shrink-0 rounded p-1 text-muted-foreground hover:text-primary transition-colors"
                  title="Edit message"
                >
                  <Pencil className="size-3.5" />
                </button>
              )}
            </div>
          )}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}
