import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { PageLayout } from "@/components/PageLayout";
import { supabase } from "@/integrations/supabase/client";
import { sendSms, flushPendingSms, sendGroupSms, queueDueReminders } from "@/lib/sms.functions";
import { usePermissions } from "@/hooks/use-permissions";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { MessageSquare, Send, Settings as SettingsIcon, RefreshCw, Users, BarChart3, AlertCircle } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { useLanguage } from "@/hooks/use-language";

export const Route = createFileRoute("/_authenticated/sms")({
  head: () => ({ meta: [{ title: "SMS — Niyamah ERP" }] }),
  component: SmsPage,
});

type Customer = { id: string; name: string; mobile: string };
type SmsLog = {
  id: string;
  customer_id: string | null;
  phone: string;
  message: string;
  type: string;
  status: string;
  reference_id: string | null;
  error_message: string | null;
  created_at: string;
  sent_at: string | null;
};
type SmsSettings = {
  id: string;
  provider: string;
  api_token: string;
  api_secret: string;
  sender_id: string;
  base_url: string;
  sms_enabled: boolean;
  auto_invoice_enabled: boolean;
  auto_payment_enabled: boolean;
  auto_delivery_enabled: boolean;
  auto_due_enabled: boolean;
  due_min_amount: number;
  invoice_template: string;
  payment_template: string;
  due_template: string;
  delivery_template: string;
};

function StatusBadge({ status }: { status: string }) {
  const variants: Record<string, string> = {
    sent: "bg-emerald-100 text-emerald-700 border-emerald-200",
    pending: "bg-amber-100 text-amber-700 border-amber-200",
    failed: "bg-red-100 text-red-700 border-red-200",
  };
  return (
    <Badge variant="outline" className={variants[status] || ""}>
      {status}
    </Badge>
  );
}

function SmsPage() {
  const { isAdmin } = usePermissions();
  const { tr } = useLanguage();
  return (
    <PageLayout title={tr("smsModule")} subtitle={tr("smsSubtitle")}>
      <Tabs defaultValue="send" className="space-y-4">
        <TabsList>
          <TabsTrigger value="send"><Send className="h-4 w-4 mr-2" /> {tr("smsSend")}</TabsTrigger>
          <TabsTrigger value="group"><Users className="h-4 w-4 mr-2" /> {tr("smsGroup")}</TabsTrigger>
          <TabsTrigger value="logs"><MessageSquare className="h-4 w-4 mr-2" /> {tr("smsLogs")}</TabsTrigger>
          <TabsTrigger value="report"><BarChart3 className="h-4 w-4 mr-2" /> {tr("smsReportTab")}</TabsTrigger>
          {isAdmin && (
            <TabsTrigger value="settings"><SettingsIcon className="h-4 w-4 mr-2" /> {tr("smsSettingsTab")}</TabsTrigger>
          )}
        </TabsList>

        <TabsContent value="send"><SendTab /></TabsContent>
        <TabsContent value="group"><GroupTab /></TabsContent>
        <TabsContent value="logs"><LogsTab /></TabsContent>
        <TabsContent value="report"><ReportTab /></TabsContent>
        {isAdmin && <TabsContent value="settings"><SettingsTab /></TabsContent>}
      </Tabs>
    </PageLayout>
  );
}

function SendTab() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [customerId, setCustomerId] = useState<string>("");
  const [phone, setPhone] = useState("");
  const [message, setMessage] = useState("");
  const [sending, setSending] = useState(false);
  const sendFn = useServerFn(sendSms);
  const flushFn = useServerFn(flushPendingSms);

  useEffect(() => {
    supabase
      .from("customers")
      .select("id, name, mobile")
      .is("deleted_at", null)
      .order("name")
      .limit(500)
      .then(({ data }) => setCustomers(data || []));
  }, []);

  const onPickCustomer = (id: string) => {
    setCustomerId(id);
    const c = customers.find((x) => x.id === id);
    if (c) setPhone(c.mobile);
  };

  const onSend = async () => {
    if (!phone.trim() || !message.trim()) {
      toast.error("Phone and message are required");
      return;
    }
    setSending(true);
    try {
      const res = await sendFn({
        data: {
          customer_id: customerId || null,
          phone: phone.trim(),
          message: message.trim(),
          type: "manual",
        },
      });
      if (res.ok) {
        toast.success("SMS sent");
        setMessage("");
      } else {
        toast.error(res.error || "Failed to send SMS");
      }
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Send failed");
    } finally {
      setSending(false);
    }
  };

  const onFlush = async () => {
    try {
      const res = await flushFn({});
      if (res.skipped) {
        toast.message("SMS disabled or not configured");
      } else {
        toast.success(`Processed ${res.processed} (sent ${res.sent}, failed ${res.failed})`);
      }
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Flush failed");
    }
  };

  const { tr } = useLanguage();
  return (
    <div className="grid gap-4 md:grid-cols-3">
      <div className="md:col-span-2 rounded-xl border border-border bg-card p-6 space-y-4">
        <h2 className="text-lg font-semibold">{tr("smsCompose")}</h2>

        <div className="space-y-2">
          <Label>{tr("smsCustomerOpt")}</Label>
          <Select value={customerId} onValueChange={onPickCustomer}>
            <SelectTrigger>
              <SelectValue placeholder={tr("smsPickCustomer")} />
            </SelectTrigger>
            <SelectContent>
              {customers.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {c.name} — {c.mobile}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-2">
          <Label>{tr("smsPhoneLabel")}</Label>
          <Input
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            placeholder="01700000000"
            maxLength={14}
          />
        </div>

        <div className="space-y-2">
          <Label>{tr("smsMessageLabel")}</Label>
          <Textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder={tr("smsMessagePlaceholder")}
            rows={5}
            maxLength={1000}
          />
          <p className="text-xs text-muted-foreground">{message.length} / 1000 {tr("smsCharCount")}</p>
        </div>

        <div className="flex gap-2">
          <Button onClick={onSend} disabled={sending}>
            <Send className="h-4 w-4 mr-2" />
            {sending ? tr("smsSending") : tr("smsSendBtn")}
          </Button>
          <Button variant="outline" onClick={onFlush}>
            <RefreshCw className="h-4 w-4 mr-2" /> {tr("smsFlushQueue")}
          </Button>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card p-6 space-y-3">
        <h3 className="font-semibold">{tr("smsPlaceholders")}</h3>
        <ul className="text-sm text-muted-foreground space-y-1">
          <li><code>{"{name}"}</code> — {tr("smsTplCustomerName")}</li>
          <li><code>{"{invoice}"}</code> / <code>{"{invoice_no}"}</code> — {tr("smsTplOrderNo")}</li>
          <li><code>{"{bill}"}</code> / <code>{"{amount}"}</code> — {tr("smsTplAmount")}</li>
          <li><code>{"{paid}"}</code> / <code>{"{received}"}</code> — {tr("smsTplPaid")}</li>
          <li><code>{"{due}"}</code> / <code>{"{current_due}"}</code> — {tr("smsTplDue")}</li>
          <li><code>{"{previous_due}"}</code> — {tr("smsTplPrevDue")}</li>
          <li><code>{"{status}"}</code> — {tr("smsTplStatus")}</li>
        </ul>
        <p className="text-xs text-muted-foreground pt-2 border-t">
          {tr("smsAutoInfo")}
        </p>
      </div>
    </div>
  );
}


function LogsTab() {
  const [logs, setLogs] = useState<SmsLog[]>([]);
  const [filter, setFilter] = useState<string>("all");
  const [loading, setLoading] = useState(true);

  const load = async () => {
    setLoading(true);
    let q = supabase.from("sms_logs").select("*").order("created_at", { ascending: false }).limit(200);
    if (filter !== "all") q = q.eq("status", filter);
    const { data } = await q;
    setLogs((data || []) as SmsLog[]);
    setLoading(false);
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filter]);

  const counts = useMemo(() => {
    const c = { sent: 0, pending: 0, failed: 0 };
    logs.forEach((l) => {
      if (l.status in c) (c as Record<string, number>)[l.status]++;
    });
    return c;
  }, [logs]);

  const { tr } = useLanguage();
  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <Select value={filter} onValueChange={setFilter}>
          <SelectTrigger className="w-48">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{tr("smsAll")}</SelectItem>
            <SelectItem value="sent">{tr("smsSent")}</SelectItem>
            <SelectItem value="pending">{tr("smsPending")}</SelectItem>
            <SelectItem value="failed">{tr("smsFailed")}</SelectItem>
          </SelectContent>
        </Select>
        <Button variant="outline" size="sm" onClick={load}>
          <RefreshCw className="h-4 w-4 mr-2" /> {tr("smsRefresh")}
        </Button>
        <div className="ml-auto flex gap-2 text-xs">
          <Badge variant="outline" className="bg-emerald-50">{tr("smsSent")}: {counts.sent}</Badge>
          <Badge variant="outline" className="bg-amber-50">{tr("smsPending")}: {counts.pending}</Badge>
          <Badge variant="outline" className="bg-red-50">{tr("smsFailed")}: {counts.failed}</Badge>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-muted/50">
            <tr className="text-left">
              <th className="p-3">{tr("smsDate")}</th>
              <th className="p-3">{tr("smsPhoneLabel")}</th>
              <th className="p-3">{tr("smsType")}</th>
              <th className="p-3">{tr("smsMessageLabel")}</th>
              <th className="p-3">{tr("smsStatusCol")}</th>
              <th className="p-3">{tr("smsNote")}</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={6} className="p-8 text-center text-muted-foreground">
                  {tr("smsLoading")}
                </td>
              </tr>
            ) : logs.length === 0 ? (
              <tr>
                <td colSpan={6} className="p-8 text-center text-muted-foreground">
                  {tr("smsNoLogs")}
                </td>
              </tr>

            ) : (
              logs.map((l) => (
                <tr key={l.id} className="border-t border-border">
                  <td className="p-3 whitespace-nowrap text-xs">
                    {new Date(l.created_at).toLocaleString()}
                  </td>
                  <td className="p-3 font-mono text-xs">{l.phone}</td>
                  <td className="p-3 text-xs uppercase">{l.type}</td>
                  <td className="p-3 max-w-md truncate" title={l.message}>{l.message}</td>
                  <td className="p-3"><StatusBadge status={l.status} /></td>
                  <td className="p-3 text-xs text-muted-foreground max-w-xs truncate" title={l.error_message || l.reference_id || ""}>
                    {l.error_message || l.reference_id || "—"}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SettingsTab() {
  const [s, setS] = useState<SmsSettings | null>(null);
  const [saving, setSaving] = useState(false);
  const { tr } = useLanguage();

  useEffect(() => {
    supabase
      .from("sms_settings")
      .select("*")
      .limit(1)
      .maybeSingle()
      .then(({ data }) => setS(data as SmsSettings | null));
  }, []);

  if (!s) {
    return <div className="text-muted-foreground">{tr("smsLoadingSettings")}</div>;
  }


  const update = <K extends keyof SmsSettings>(key: K, val: SmsSettings[K]) =>
    setS((prev) => (prev ? { ...prev, [key]: val } : prev));

  const onSave = async () => {
    setSaving(true);
    const { error } = await supabase
      .from("sms_settings")
      .update({
        provider: s.provider,
        api_token: s.api_token,
        api_secret: s.api_secret,
        sender_id: s.sender_id,
        base_url: s.base_url,
        sms_enabled: s.sms_enabled,
        auto_invoice_enabled: s.auto_invoice_enabled,
        auto_payment_enabled: s.auto_payment_enabled,
        auto_delivery_enabled: s.auto_delivery_enabled,
        auto_due_enabled: s.auto_due_enabled,
        due_min_amount: s.due_min_amount,
        invoice_template: s.invoice_template,
        payment_template: s.payment_template,
        due_template: s.due_template,
        delivery_template: s.delivery_template,
      })
      .eq("id", s.id);
    setSaving(false);
    if (error) toast.error(error.message);
    else toast.success("Settings saved");
  };

  return (
    <div className="grid gap-4 md:grid-cols-2">
      <div className="rounded-xl border border-border bg-card p-6 space-y-4">
        <h2 className="text-lg font-semibold">{tr("smsGateway")}</h2>

        <div className="flex items-center justify-between">
          <Label>{tr("smsEnabled")}</Label>
          <Switch checked={s.sms_enabled} onCheckedChange={(v) => update("sms_enabled", v)} />
        </div>
        <div className="flex items-center justify-between">
          <Label>{tr("smsAutoInvoice")}</Label>
          <Switch checked={s.auto_invoice_enabled} onCheckedChange={(v) => update("auto_invoice_enabled", v)} />
        </div>
        <div className="flex items-center justify-between">
          <Label>{tr("smsAutoPayment")}</Label>
          <Switch checked={s.auto_payment_enabled} onCheckedChange={(v) => update("auto_payment_enabled", v)} />
        </div>
        <div className="flex items-center justify-between">
          <Label>{tr("smsAutoDelivery")}</Label>
          <Switch checked={s.auto_delivery_enabled} onCheckedChange={(v) => update("auto_delivery_enabled", v)} />
        </div>
        <div className="flex items-center justify-between">
          <Label>{tr("smsAutoDue")}</Label>
          <Switch checked={s.auto_due_enabled} onCheckedChange={(v) => update("auto_due_enabled", v)} />
        </div>
        <div className="space-y-2">
          <Label>{tr("smsMinDue")}</Label>
          <Input
            type="number"
            value={s.due_min_amount}
            onChange={(e) => update("due_min_amount", Number(e.target.value) || 0)}
          />
        </div>

        <div className="space-y-2">
          <Label>{tr("smsProvider")}</Label>
          <Select value={s.provider} onValueChange={(v) => update("provider", v)}>
            <SelectTrigger><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="ssl_wireless">SSL Wireless</SelectItem>
              <SelectItem value="tqlsolved">TQL Solved (sms.tqlsolved.com)</SelectItem>
            </SelectContent>
          </Select>
          {s.provider === "tqlsolved" && (
            <p className="text-xs text-muted-foreground">
              API URL: <code>https://sms.tqlsolved.com/smsapi</code> · Username = আপনার <strong>লগইন ইমেইল</strong> · Password = লগইন পাসওয়ার্ড · Sender ID = <strong>Gateway ID</strong> (Gateway &amp; Price পেজ থেকে দেখুন, যেমন <code>6688f7d31f5d8</code>)
            </p>
          )}
        </div>



        <div className="space-y-2">
          <Label>{tr("smsApiUrl")}</Label>
          <Input value={s.base_url} onChange={(e) => update("base_url", e.target.value)} />
        </div>
        {s.provider === "tqlsolved" && (
          <div className="space-y-2">
            <Label>Username (Email)</Label>
            <Input
              type="email"
              value={s.api_secret}
              onChange={(e) => update("api_secret", e.target.value)}
              placeholder="example@host.com"
            />
          </div>
        )}
        <div className="space-y-2">
          <Label>{s.provider === "tqlsolved" ? "Password" : tr("smsApiToken")}</Label>
          <Input
            type="password"
            value={s.api_token}
            onChange={(e) => update("api_token", e.target.value)}
            placeholder={s.provider === "tqlsolved" ? "লগইন পাসওয়ার্ড" : tr("smsTokenPlaceholder")}
          />
        </div>
        <div className="space-y-2">
          <Label>{s.provider === "tqlsolved" ? "Gateway ID" : tr("smsSenderId")}</Label>
          <Input
            value={s.sender_id}
            onChange={(e) => update("sender_id", e.target.value)}
            placeholder={s.provider === "tqlsolved" ? "যেমন 6688f7d31f5d8" : tr("smsSenderPlaceholder")}
          />
        </div>

        <Button onClick={onSave} disabled={saving}>
          {saving ? tr("smsSaving") : tr("smsSave")}
        </Button>
      </div>

      <div className="rounded-xl border border-border bg-card p-6 space-y-4">
        <h2 className="text-lg font-semibold">{tr("smsTemplates")}</h2>
        <p className="text-xs text-muted-foreground">
          {tr("smsTplPlaceholdersHint")} <code>{"{name}"}</code>, <code>{"{invoice_no}"}</code>,{" "}
          <code>{"{amount}"}</code>, <code>{"{due}"}</code>, <code>{"{status}"}</code>,{" "}
          <code>{"{previous_due}"}</code>, <code>{"{received}"}</code>, <code>{"{current_due}"}</code>
        </p>

        <div className="space-y-2">
          <Label>{tr("smsInvoiceTpl")}</Label>
          <Textarea
            rows={7}
            value={s.invoice_template}
            onChange={(e) => update("invoice_template", e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label>{tr("smsPaymentTpl")}</Label>
          <Textarea
            rows={2}
            value={s.payment_template}
            onChange={(e) => update("payment_template", e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label>{tr("smsDueTpl")}</Label>
          <Textarea
            rows={2}
            value={s.due_template}
            onChange={(e) => update("due_template", e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label>{tr("smsDeliveryTpl")}</Label>
          <Textarea
            rows={2}
            value={s.delivery_template}
            onChange={(e) => update("delivery_template", e.target.value)}
          />
        </div>
      </div>
    </div>
  );
}


type GroupCustomer = { id: string; name: string; mobile: string; total_due: number };

function GroupTab() {
  const [customers, setCustomers] = useState<GroupCustomer[]>([]);
  const [selected, setSelected] = useState<Record<string, boolean>>({});
  const [filter, setFilter] = useState<"all" | "due" | "active">("all");
  const [search, setSearch] = useState("");
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const groupFn = useServerFn(sendGroupSms);
  const dueFn = useServerFn(queueDueReminders);
  const flushFn = useServerFn(flushPendingSms);
  const { tr } = useLanguage();


  useEffect(() => {
    supabase
      .from("customers")
      .select("id, name, mobile, total_due")
      .is("deleted_at", null)
      .order("name")
      .limit(1000)
      .then(({ data }) => setCustomers((data || []) as GroupCustomer[]));
  }, []);

  const filtered = useMemo(() => {
    return customers.filter((c) => {
      if (filter === "due" && (c.total_due ?? 0) <= 0) return false;
      if (filter === "active" && (c.total_due ?? 0) > 0) return false;
      if (search && !`${c.name} ${c.mobile}`.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [customers, filter, search]);

  const selectedCount = Object.values(selected).filter(Boolean).length;

  const toggleAll = (v: boolean) => {
    const next: Record<string, boolean> = {};
    if (v) filtered.forEach((c) => (next[c.id] = true));
    setSelected(next);
  };

  const onSend = async () => {
    const ids = Object.entries(selected).filter(([, v]) => v).map(([k]) => k);
    if (!ids.length || !message.trim()) {
      toast.error("Select customers and write a message");
      return;
    }
    setBusy(true);
    try {
      const res = await groupFn({ data: { customer_ids: ids, message: message.trim() } });
      if (res.ok) {
        toast.success(`Queued ${res.queued} SMS (skipped ${res.skipped ?? 0})`);
        await flushFn({});
        setSelected({});
        setMessage("");
      } else {
        toast.error(res.error || "Failed");
      }
    } finally {
      setBusy(false);
    }
  };

  const onSendDueAll = async () => {
    setBusy(true);
    try {
      const res = await dueFn({});
      if (res.ok) {
        toast.success(`Queued ${res.queued} due reminders`);
        await flushFn({});
      } else {
        toast.error(res.error || "Failed");
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="grid gap-4 md:grid-cols-3">
      <div className="md:col-span-2 rounded-xl border border-border bg-card p-6 space-y-4">
        <div className="flex flex-wrap gap-2 items-center">
          <Input placeholder={tr("smsSearch")} value={search} onChange={(e) => setSearch(e.target.value)} className="max-w-xs" />
          <Select value={filter} onValueChange={(v) => setFilter(v as typeof filter)}>
            <SelectTrigger className="w-40"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{tr("smsAll")}</SelectItem>
              <SelectItem value="due">{tr("smsWithDue")}</SelectItem>
              <SelectItem value="active">{tr("smsNoDue")}</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" size="sm" onClick={() => toggleAll(true)}>{tr("smsSelectFiltered")}</Button>
          <Button variant="outline" size="sm" onClick={() => toggleAll(false)}>{tr("smsClear")}</Button>
          <span className="ml-auto text-sm text-muted-foreground">{tr("smsSelected")}: {selectedCount}</span>
        </div>
        <div className="rounded border border-border max-h-96 overflow-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 sticky top-0">
              <tr className="text-left">
                <th className="p-2 w-8"></th>
                <th className="p-2">{tr("smsName")}</th>
                <th className="p-2">{tr("smsMobile")}</th>
                <th className="p-2 text-right">{tr("smsDue")}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((c) => (
                <tr key={c.id} className="border-t border-border">
                  <td className="p-2">
                    <Checkbox
                      checked={!!selected[c.id]}
                      onCheckedChange={(v) => setSelected((p) => ({ ...p, [c.id]: !!v }))}
                    />
                  </td>
                  <td className="p-2">{c.name}</td>
                  <td className="p-2 font-mono text-xs">{c.mobile}</td>
                  <td className="p-2 text-right">{Number(c.total_due ?? 0).toFixed(2)}</td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={4} className="p-6 text-center text-muted-foreground">{tr("smsNoCustomers")}</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
      <div className="rounded-xl border border-border bg-card p-6 space-y-4">
        <h3 className="font-semibold">{tr("smsComposeShort")}</h3>
        <Textarea
          rows={6}
          maxLength={1000}
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder={tr("smsGroupPlaceholder")}
        />
        <p className="text-xs text-muted-foreground">{tr("smsTplPlaceholdersHint")} {"{name}"}, {"{due}"}</p>
        <Button onClick={onSend} disabled={busy || selectedCount === 0}>
          <Send className="h-4 w-4 mr-2" /> {tr("smsQueueSendTo")} {selectedCount}
        </Button>
        <div className="pt-3 border-t space-y-2">
          <p className="text-xs text-muted-foreground flex items-start gap-1">
            <AlertCircle className="h-3 w-3 mt-0.5" />
            {tr("smsDueAllHint")}
          </p>
          <Button variant="outline" onClick={onSendDueAll} disabled={busy} className="w-full">
            {tr("smsSendDueAll")}
          </Button>
        </div>
      </div>
    </div>
  );
}


function ReportTab() {
  const { tr } = useLanguage();
  const [stats, setStats] = useState<{
    total: number;
    sent: number;
    pending: number;
    failed: number;
    byType: Record<string, number>;
    daily: Array<{ date: string; count: number }>;
  } | null>(null);

  useEffect(() => {
    (async () => {
      const since = new Date(Date.now() - 30 * 24 * 3600 * 1000).toISOString();
      const { data } = await supabase
        .from("sms_logs")
        .select("status, type, created_at")
        .gte("created_at", since)
        .limit(5000);
      const rows = data || [];
      const byType: Record<string, number> = {};
      const daily: Record<string, number> = {};
      let sent = 0, pending = 0, failed = 0;
      rows.forEach((r) => {
        byType[r.type] = (byType[r.type] || 0) + 1;
        const d = (r.created_at || "").slice(0, 10);
        daily[d] = (daily[d] || 0) + 1;
        if (r.status === "sent") sent++;
        else if (r.status === "pending") pending++;
        else if (r.status === "failed") failed++;
      });
      const dailyArr = Object.entries(daily)
        .sort((a, b) => a[0].localeCompare(b[0]))
        .map(([date, count]) => ({ date, count }));
      setStats({ total: rows.length, sent, pending, failed, byType, daily: dailyArr });
    })();
  }, []);

  if (!stats) return <div className="text-muted-foreground">{tr("smsLoadingReport")}</div>;

  const maxDaily = Math.max(1, ...stats.daily.map((d) => d.count));

  return (
    <div className="space-y-4">
      <div className="grid gap-3 md:grid-cols-4">
        {[
          { label: tr("smsTotal30d"), value: stats.total, cls: "bg-card" },
          { label: tr("smsSent"), value: stats.sent, cls: "bg-emerald-50 dark:bg-emerald-950/30" },
          { label: tr("smsPending"), value: stats.pending, cls: "bg-amber-50 dark:bg-amber-950/30" },
          { label: tr("smsFailed"), value: stats.failed, cls: "bg-red-50 dark:bg-red-950/30" },
        ].map((c) => (
          <div key={c.label} className={`rounded-xl border border-border p-4 ${c.cls}`}>
            <div className="text-xs text-muted-foreground">{c.label}</div>
            <div className="text-2xl font-semibold">{c.value}</div>
          </div>
        ))}
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <div className="rounded-xl border border-border bg-card p-6">
          <h3 className="font-semibold mb-3">{tr("smsByType")}</h3>
          <div className="space-y-2">
            {Object.entries(stats.byType).map(([t, c]) => (
              <div key={t} className="flex items-center justify-between text-sm">
                <span className="uppercase">{t}</span>
                <Badge variant="outline">{c}</Badge>
              </div>
            ))}
            {Object.keys(stats.byType).length === 0 && (
              <p className="text-sm text-muted-foreground">{tr("smsNoData")}</p>
            )}
          </div>
        </div>
        <div className="rounded-xl border border-border bg-card p-6">
          <h3 className="font-semibold mb-3">{tr("smsDaily")}</h3>
          <div className="space-y-1">
            {stats.daily.slice(-14).map((d) => (
              <div key={d.date} className="flex items-center gap-2 text-xs">
                <span className="w-20 text-muted-foreground">{d.date}</span>
                <div className="flex-1 h-3 bg-muted rounded overflow-hidden">
                  <div className="h-full bg-primary" style={{ width: `${(d.count / maxDaily) * 100}%` }} />
                </div>
                <span className="w-8 text-right tabular-nums">{d.count}</span>
              </div>
            ))}
            {stats.daily.length === 0 && (
              <p className="text-sm text-muted-foreground">{tr("smsNoData")}</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
