import { useState, useEffect, useRef } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Bot, CalendarCheck, UserPlus, MessageCircle, Info, CalendarX } from "lucide-react";
const SUPPORTED_SMS_VARS = [
    "{firstName}", "{officeName}", "{appointmentDate}", "{appointmentTime}", "{date}", "{time}",
];
const DEFAULTS = {
    reminderSms: "Hi {firstName}, this is a reminder from {officeName}. You have an appointment on {appointmentDate} at {appointmentTime}. Please reply YES to confirm or NO to reschedule. Thank you!",
    reminderGreeting: "Hi! My name is Lisa, the dedicated AI assistant at {officeName}. I can confirm or reschedule your appointment and answer general questions 24/7. I will reply to your message at any time you need.",
    newPatientGreeting: "Hi! My name is Lisa, the dedicated AI assistant at {officeName}. I can help you schedule an appointment, check your insurance, and answer general questions 24/7. How can I help you today?",
    generalFallback: "Hi! My name is Lisa, the dedicated AI assistant at {officeName}. How can I help you today?",
    rescheduleGreeting: "It is understandable! When would you like to reschedule your appointment?",
};
function preview(text, officeName) {
    return text.replace(/\{officeName\}/g, officeName || "your dental office");
}
/** Returns any {variable} tokens in `text` that are not in the supported list. */
function unsupportedVars(text) {
    const found = text.match(/\{[^}]+\}/g) ?? [];
    return [...new Set(found)].filter((v) => !SUPPORTED_SMS_VARS.includes(v));
}
/** True if text starts with a self-introduction ("Hi! My name is Lisa…"). */
function hasIntroPattern(text) {
    return /^(Hi[!,]?\s*)?(My name is|I'?m|I am)\s+/i.test(text.trim());
}
export function AiChatTemplatesCard() {
    const { toast } = useToast();
    const [reminderSms, setReminderSms] = useState(DEFAULTS.reminderSms);
    const [reminderGreeting, setReminderGreeting] = useState(DEFAULTS.reminderGreeting);
    const [newPatientGreeting, setNewPatientGreeting] = useState(DEFAULTS.newPatientGreeting);
    const [generalFallback, setGeneralFallback] = useState(DEFAULTS.generalFallback);
    const [rescheduleGreeting, setRescheduleGreeting] = useState(DEFAULTS.rescheduleGreeting);
    const initialized = useRef(false);
    const { data: officeContact } = useQuery({
        queryKey: ["/api/office-contact"],
        queryFn: async () => {
            const res = await apiRequest("GET", "/api/office-contact");
            if (!res.ok)
                return null;
            return res.json();
        },
        staleTime: 60_000,
    });
    const { data: templates, isLoading } = useQuery({
        queryKey: ["/api/ai/chat-templates"],
        queryFn: async () => {
            const res = await apiRequest("GET", "/api/ai/chat-templates");
            if (!res.ok)
                throw new Error("Failed to load templates");
            return res.json();
        },
        staleTime: Infinity, // never silently refetch and overwrite user edits
        refetchOnWindowFocus: false,
    });
    // Seed state from server on first successful load only
    useEffect(() => {
        if (templates && !initialized.current) {
            initialized.current = true;
            setReminderSms(templates.reminderSms || DEFAULTS.reminderSms);
            setReminderGreeting(templates.reminderGreeting || DEFAULTS.reminderGreeting);
            setNewPatientGreeting(templates.newPatientGreeting || DEFAULTS.newPatientGreeting);
            setGeneralFallback(templates.generalFallback || DEFAULTS.generalFallback);
            setRescheduleGreeting(templates.rescheduleGreeting || DEFAULTS.rescheduleGreeting);
        }
    }, [templates]);
    const saveMutation = useMutation({
        mutationFn: async (data) => {
            const res = await apiRequest("PUT", "/api/ai/chat-templates", data);
            if (!res.ok) {
                const err = await res.json().catch(() => null);
                throw new Error(err?.message || "Failed to save templates");
            }
            return res.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["/api/ai/chat-templates"] });
            toast({ title: "Templates saved", description: "AI chat templates have been updated." });
        },
        onError: (err) => {
            toast({ title: "Error", description: err?.message, variant: "destructive" });
        },
    });
    const handleSubmit = (e) => {
        e.preventDefault();
        saveMutation.mutate({
            reminderSms: reminderSms.trim() || DEFAULTS.reminderSms,
            reminderGreeting: reminderGreeting.trim() || DEFAULTS.reminderGreeting,
            newPatientGreeting: newPatientGreeting.trim() || DEFAULTS.newPatientGreeting,
            generalFallback: generalFallback.trim() || DEFAULTS.generalFallback,
            rescheduleGreeting: rescheduleGreeting.trim() || DEFAULTS.rescheduleGreeting,
        });
    };
    const officeName = officeContact?.officeName?.trim() || "";
    const templates_list = [
        {
            key: "reminderSms",
            icon: <CalendarCheck className="h-4 w-4 text-primary"/>,
            label: "Reminder SMS Text",
            description: "Outgoing text sent from the Schedule page. Supported variables: {firstName}, {officeName}, {appointmentDate}, {appointmentTime}, {date}, {time}. Any other {variable} will be sent as plain text.",
            value: reminderSms,
            onChange: setReminderSms,
            placeholder: DEFAULTS.reminderSms,
        },
        {
            key: "reminder",
            icon: <CalendarCheck className="h-4 w-4 text-primary"/>,
            label: "Appointment Reminder Reply",
            description: "Sent when the AI introduces itself after the office sends an appointment reminder.",
            value: reminderGreeting,
            onChange: setReminderGreeting,
            placeholder: DEFAULTS.reminderGreeting,
        },
        {
            key: "newPatient",
            icon: <UserPlus className="h-4 w-4 text-primary"/>,
            label: "New Patient Greeting",
            description: "Sent when a new patient texts in for the first time.",
            value: newPatientGreeting,
            onChange: setNewPatientGreeting,
            placeholder: DEFAULTS.newPatientGreeting,
        },
        {
            key: "general",
            icon: <MessageCircle className="h-4 w-4 text-primary"/>,
            label: "General Fallback",
            description: "Used when the AI cannot determine the context of the patient's message.",
            value: generalFallback,
            onChange: setGeneralFallback,
            placeholder: DEFAULTS.generalFallback,
        },
        {
            key: "reschedule",
            icon: <CalendarX className="h-4 w-4 text-primary"/>,
            label: "Reschedule Patients",
            description: "Sent when the office initiates a reschedule flow for a patient.",
            value: rescheduleGreeting,
            onChange: setRescheduleGreeting,
            placeholder: DEFAULTS.rescheduleGreeting,
        },
    ];
    return (<Card>
      <CardContent className="py-6 space-y-6">
        {/* Header */}
        <div className="flex items-center gap-2">
          <Bot className="h-5 w-5 text-primary"/>
          <h3 className="text-lg font-semibold">AI Chat Templates</h3>
        </div>
        <p className="text-sm text-muted-foreground">
          Customize the reminder SMS and AI reply templates. Available variables:{" "}
          <code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{firstName}"}</code>{" "}
          <code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{officeName}"}</code>{" "}
          <code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{appointmentDate}"}</code>{" "}
          <code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{appointmentTime}"}</code>{" "}
          — replaced automatically when reminders are sent.
        </p>

        {/* Office name hint */}
        {officeName && (<div className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/50 rounded px-3 py-2">
            <Info className="h-3.5 w-3.5 flex-shrink-0"/>
            <span>
              <span className="font-medium">{"{officeName}"}</span> will display as{" "}
              <span className="font-medium text-foreground">"{officeName}"</span>
            </span>
          </div>)}

        {isLoading ? (<p className="text-sm text-muted-foreground">Loading templates...</p>) : (<form onSubmit={handleSubmit} className="space-y-6">
            {templates_list.map((t) => {
                const badVars = t.key === "reminderSms" ? unsupportedVars(t.value) : [];
                const hasIntro = t.key === "reschedule" && hasIntroPattern(t.value);
                const hasWarn = badVars.length > 0 || hasIntro;
                return (<div key={t.key} className="space-y-2">
                  <div className="flex items-center gap-2">
                    {t.icon}
                    <span className="text-sm font-medium">{t.label}</span>
                  </div>
                  <p className="text-xs text-muted-foreground">{t.description}</p>
                  <Textarea value={t.value} onChange={(e) => t.onChange(e.target.value)} placeholder={t.placeholder} rows={3} className={`text-sm resize-none ${hasWarn ? "border-amber-400 focus-visible:ring-amber-400" : ""}`}/>
                  {/* Unsupported variable warning */}
                  {badVars.length > 0 && (<div className="flex items-start gap-2 rounded-md bg-amber-50 border border-amber-300 px-3 py-2 text-xs text-amber-800">
                      <span className="mt-0.5">⚠️</span>
                      <span>
                        <strong>Unsupported variable{badVars.length > 1 ? "s" : ""}:</strong>{" "}
                        {badVars.join(", ")} — {badVars.length > 1 ? "these" : "this"} will be sent as plain text to patients.
                        Supported: {SUPPORTED_SMS_VARS.join(", ")}.
                      </span>
                    </div>)}
                  {/* Self-intro warning for reschedule greeting */}
                  {hasIntro && (<div className="flex items-start gap-2 rounded-md bg-amber-50 border border-amber-300 px-3 py-2 text-xs text-amber-800">
                      <span className="mt-0.5">⚠️</span>
                      <span>
                        This template starts with a self-introduction ("Hi! My name is Lisa…").
                        The AI introduction is already sent as a <strong>separate first message</strong> —
                        this template is only used as the <strong>second message</strong> (the intent response).
                        Remove the intro to avoid the patient receiving "My name is Lisa…" twice.
                      </span>
                    </div>)}
                  {/* Live preview */}
                  {officeName && t.value.includes("{officeName}") && (<p className="text-xs text-muted-foreground italic pl-1">
                      Preview: {preview(t.value, officeName)}
                    </p>)}
                </div>);
            })}

            <div className="flex items-center gap-3 pt-2">
              <Button type="submit" disabled={saveMutation.isPending} className="bg-teal-600 hover:bg-teal-700 text-white">
                {saveMutation.isPending ? "Saving..." : "Save Templates"}
              </Button>
              <Button type="button" variant="ghost" className="text-xs text-muted-foreground" onClick={() => {
                setReminderSms(DEFAULTS.reminderSms);
                setReminderGreeting(DEFAULTS.reminderGreeting);
                setNewPatientGreeting(DEFAULTS.newPatientGreeting);
                setGeneralFallback(DEFAULTS.generalFallback);
                setRescheduleGreeting(DEFAULTS.rescheduleGreeting);
            }}>
                Reset to defaults
              </Button>
            </div>
          </form>)}
      </CardContent>
    </Card>);
}
