// @File: src/pages/ClientWhatsappAi.tsx
// @Desc: Client-area AI Auto-Reply console for the WhatsApp Business
//        Reseller module. Lets the client configure knowledge base, tone,
//        language, business hours, and quality toggles, then preview a
//        reply against a sample incoming message before flipping auto-
//        reply on. Pure shadcn/ui + Tailwind.
import { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, Sparkles, AlertCircle, CheckCircle2, MessageSquare } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";

import {
  waGetAiSettings,
  waPreviewAiReply,
  waUpdateAiSettings,
  type WhatsappAiPreviewResult,
  type WhatsappAiSettings,
} from "@/lib/whatsappApi";

const TONE_OPTIONS: Array<{ value: WhatsappAiSettings["tone"]; label: string }> = [
  { value: "friendly", label: "Friendly" },
  { value: "professional", label: "Professional" },
  { value: "concise", label: "Concise" },
  { value: "casual", label: "Casual" },
];

const LANGUAGE_OPTIONS: Array<{ value: WhatsappAiSettings["language"]; label: string }> = [
  { value: "en", label: "English" },
  { value: "ar", label: "العربية (Arabic)" },
  { value: "auto", label: "Auto-detect" },
];

export default function ClientWhatsappAi() {
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [settings, setSettings] = useState<WhatsappAiSettings | null>(null);

  const [previewInput, setPreviewInput] = useState(
    "Hi, do you have any packages for 50 monthly messages?",
  );
  const [preview, setPreview] = useState<WhatsappAiPreviewResult | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  // Debounced auto-save: when the user edits text fields, persist 800ms
  // after the last change so they don't need to click a Save button for
  // every toggle. Switch/Select changes save immediately via patchField.
  const saveTimer = useRef<number | null>(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const data = await waGetAiSettings();
        if (mounted) setSettings(data);
      } catch (err) {
        if (mounted)
          setError(err instanceof Error ? err.message : "Failed to load AI settings.");
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => {
      mounted = false;
      if (saveTimer.current) window.clearTimeout(saveTimer.current);
    };
  }, []);

  const updateLocal = (patch: Partial<WhatsappAiSettings>) => {
    setSettings((prev) => (prev ? { ...prev, ...patch } : prev));
  };

  const patchField = async (patch: Partial<WhatsappAiSettings>) => {
    updateLocal(patch);
    setSaving(true);
    try {
      const updated = await waUpdateAiSettings(patch);
      setSettings(updated);
    } catch (err) {
      toast({
        title: "Couldn't save",
        description: err instanceof Error ? err.message : "Try again in a moment.",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  const scheduleTextSave = (patch: Partial<WhatsappAiSettings>) => {
    updateLocal(patch);
    if (saveTimer.current) window.clearTimeout(saveTimer.current);
    saveTimer.current = window.setTimeout(() => {
      void patchField(patch);
    }, 800);
  };

  const onPreview = async () => {
    const message = previewInput.trim();
    if (!message) {
      toast({
        title: "Enter a sample message",
        description: "Type what a customer might say and we'll draft a reply.",
      });
      return;
    }
    setPreviewLoading(true);
    setPreview(null);
    try {
      const result = await waPreviewAiReply(message, true);
      setPreview(result);
    } catch (err) {
      toast({
        title: "Preview failed",
        description: err instanceof Error ? err.message : "Please try again.",
        variant: "destructive",
      });
    } finally {
      setPreviewLoading(false);
    }
  };

  const statusBadge = useMemo(() => {
    if (!settings) return null;
    return settings.auto_reply_enabled ? (
      <Badge className="bg-emerald-100 text-emerald-800 hover:bg-emerald-100">
        <CheckCircle2 className="mr-1 h-3 w-3" /> Auto-reply on
      </Badge>
    ) : (
      <Badge variant="secondary">Auto-reply off</Badge>
    );
  }, [settings]);

  if (loading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    );
  }

  if (error || !settings) {
    return (
      <div className="container mx-auto max-w-3xl py-10">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Unable to load AI settings</AlertTitle>
          <AlertDescription>
            {error ?? "No active WhatsApp subscription was found for your account."}
            <div className="mt-3">
              <Link to="/whatsapp-api" className="underline">
                View WhatsApp plans
              </Link>
            </div>
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  return (
    <div className="container mx-auto max-w-5xl space-y-6 py-8">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-primary/10 p-2 text-primary">
              <Sparkles className="h-5 w-5" />
            </div>
            <div>
              <h1 className="text-2xl font-semibold tracking-tight">AI Auto-Reply</h1>
              <p className="text-sm text-muted-foreground">
                Train the assistant on your business, then let it reply to WhatsApp
                messages instantly.
              </p>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {saving ? (
            <span className="flex items-center gap-1 text-xs text-muted-foreground">
              <Loader2 className="h-3 w-3 animate-spin" /> Saving…
            </span>
          ) : null}
          {statusBadge}
        </div>
      </div>

      {/* Main toggle */}
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between gap-4">
            <div>
              <CardTitle>Enable AI auto-reply</CardTitle>
              <CardDescription>
                When switched on, the assistant will answer incoming WhatsApp
                messages automatically using the knowledge base below.
              </CardDescription>
            </div>
            <Switch
              checked={settings.auto_reply_enabled}
              onCheckedChange={(checked) => patchField({ auto_reply_enabled: checked })}
              aria-label="Enable auto-reply"
            />
          </div>
        </CardHeader>
      </Card>

      {/* Knowledge base */}
      <Card>
        <CardHeader>
          <CardTitle>Business knowledge</CardTitle>
          <CardDescription>
            Describe your products, services, pricing, policies, and anything else
            the assistant should know. Plain text is fine — the AI will adapt.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="knowledge_base">Knowledge base</Label>
            <Textarea
              id="knowledge_base"
              value={settings.knowledge_base ?? ""}
              onChange={(e) => scheduleTextSave({ knowledge_base: e.target.value })}
              rows={8}
              placeholder={
                "Example:\nWe are a domain + hosting reseller based in Kuwait.\n" +
                "Business hours: Sun–Thu, 9am–6pm (GST).\n" +
                "Starter hosting plan is 8 KWD/month (10GB SSD, 1 domain).\n" +
                "Refund policy: 14-day money-back on annual plans."
              }
            />
            <p className="text-xs text-muted-foreground">
              Up to ~6000 characters. Longer inputs are trimmed from the end.
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="faq_training">FAQ / example Q&amp;A</Label>
            <Textarea
              id="faq_training"
              value={settings.faq_training ?? ""}
              onChange={(e) => scheduleTextSave({ faq_training: e.target.value })}
              rows={6}
              placeholder={
                "Q: How long does setup take?\nA: Most hosting accounts are ready in under 10 minutes.\n\n" +
                "Q: Do you offer Arabic support?\nA: Yes — our team replies in Arabic and English."
              }
            />
            <p className="text-xs text-muted-foreground">
              Pairs of questions and approved answers help the AI match your tone.
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Tone / language / thresholds */}
      <Card>
        <CardHeader>
          <CardTitle>Voice &amp; behaviour</CardTitle>
          <CardDescription>
            Control how the assistant sounds and when it should step aside for a
            human.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label>Tone</Label>
              <Select
                value={settings.tone}
                onValueChange={(value) => patchField({ tone: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {TONE_OPTIONS.map((o) => (
                    <SelectItem key={o.value} value={o.value}>
                      {o.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Reply language</Label>
              <Select
                value={settings.language}
                onValueChange={(value) => patchField({ language: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {LANGUAGE_OPTIONS.map((o) => (
                    <SelectItem key={o.value} value={o.value}>
                      {o.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="confidence_threshold">
              Minimum confidence (auto-send when ≥ {settings.confidence_threshold}%)
            </Label>
            <Input
              id="confidence_threshold"
              type="range"
              min={0}
              max={100}
              step={5}
              value={settings.confidence_threshold}
              onChange={(e) =>
                updateLocal({ confidence_threshold: Number(e.target.value) })
              }
              onMouseUp={() =>
                void patchField({ confidence_threshold: settings.confidence_threshold })
              }
              onTouchEnd={() =>
                void patchField({ confidence_threshold: settings.confidence_threshold })
              }
            />
            <p className="text-xs text-muted-foreground">
              Below this score the assistant queues a draft for you to approve.
            </p>
          </div>

          <Separator />

          <div className="space-y-4">
            <div className="flex items-center justify-between gap-4">
              <div>
                <Label className="text-sm">Only reply during business hours</Label>
                <p className="text-xs text-muted-foreground">
                  Outside the window below, the assistant stays silent.
                </p>
              </div>
              <Switch
                checked={settings.business_hours_only}
                onCheckedChange={(checked) =>
                  patchField({ business_hours_only: checked })
                }
              />
            </div>

            {settings.business_hours_only ? (
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="bh_start">Start</Label>
                  <Input
                    id="bh_start"
                    type="time"
                    value={settings.business_hours_start}
                    onChange={(e) =>
                      scheduleTextSave({ business_hours_start: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="bh_end">End</Label>
                  <Input
                    id="bh_end"
                    type="time"
                    value={settings.business_hours_end}
                    onChange={(e) =>
                      scheduleTextSave({ business_hours_end: e.target.value })
                    }
                  />
                </div>
              </div>
            ) : null}
          </div>
        </CardContent>
      </Card>

      {/* Quality toggles */}
      <Card>
        <CardHeader>
          <CardTitle>Quality &amp; safety</CardTitle>
          <CardDescription>
            Fine-tune how the assistant handles tricky messages.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {[
            {
              key: "human_handoff_enabled" as const,
              title: "Hand off to a human when needed",
              desc: "Refunds, escalations, and complex issues are flagged for your team.",
            },
            {
              key: "preview_before_sending" as const,
              title: "Preview drafts before sending",
              desc: "Low-confidence replies wait for you to review them.",
            },
            {
              key: "sentiment_detection_enabled" as const,
              title: "Detect customer sentiment",
              desc: "Acknowledges frustration before answering when needed.",
            },
            {
              key: "suggested_replies_enabled" as const,
              title: "Suggest replies in chat",
              desc: "Offer quick-reply chips while you type.",
            },
            {
              key: "spam_detection_enabled" as const,
              title: "Filter obvious spam",
              desc: "Decline off-topic and abusive messages politely.",
            },
            {
              key: "lead_qualification_enabled" as const,
              title: "Qualify leads with a follow-up question",
              desc: "Ask about budget, timeline, or product interest on buying intent.",
            },
          ].map((row) => (
            <div
              key={row.key}
              className="flex items-start justify-between gap-4 rounded-lg border border-border/50 p-3"
            >
              <div className="space-y-0.5">
                <Label className="text-sm">{row.title}</Label>
                <p className="text-xs text-muted-foreground">{row.desc}</p>
              </div>
              <Switch
                checked={Boolean(settings[row.key])}
                onCheckedChange={(checked) =>
                  patchField({ [row.key]: checked } as Partial<WhatsappAiSettings>)
                }
              />
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Preview panel */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-primary" />
            <CardTitle>Test reply</CardTitle>
          </div>
          <CardDescription>
            Try a sample incoming message to see how the assistant will answer.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="preview_input">Incoming message</Label>
            <Textarea
              id="preview_input"
              rows={3}
              value={previewInput}
              onChange={(e) => setPreviewInput(e.target.value)}
              placeholder="Type what a customer might send…"
            />
          </div>
          <Button onClick={onPreview} disabled={previewLoading}>
            {previewLoading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Drafting…
              </>
            ) : (
              <>
                <Sparkles className="mr-2 h-4 w-4" /> Preview reply
              </>
            )}
          </Button>

          {preview ? (
            <div className="space-y-2 rounded-lg bg-muted/40 p-4">
              {preview.gated ? (
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertTitle>Reply skipped</AlertTitle>
                  <AlertDescription>
                    {preview.reason ?? "The assistant decided not to reply."}
                  </AlertDescription>
                </Alert>
              ) : (
                <>
                  <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    Draft reply · {preview.model}
                  </p>
                  <p className="whitespace-pre-wrap rounded-md border border-border/50 bg-background p-3 text-sm">
                    {preview.reply || "(empty reply)"}
                  </p>
                </>
              )}
            </div>
          ) : null}
        </CardContent>
      </Card>
    </div>
  );
}