'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import useApprovedTemplates from '../../hooks/useApprovedTemplates';
import useBulkSend, { useCampaignProgress, useCancelCampaign } from '../../hooks/useBulkSend';
import type { PhoneReportFilters } from '../../hooks/useInfluencerPhoneReport';

/** Mirrors InfluencerPhoneReportController::MAX_RECIPIENTS. */
const MAX_RECIPIENTS = 5000;

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Explicit "platform|handle" keys; ignored when selectAll is true. */
  selected: string[];
  selectAll: boolean;
  /** Total matching the current filters (used for the select-all count). */
  matchingTotal: number;
  filters: PhoneReportFilters;
};

export default function BulkSendModal({
  open,
  onOpenChange,
  selected,
  selectAll,
  matchingTotal,
  filters,
}: Props) {
  const [templateId, setTemplateId] = useState<string>('');
  const [content, setContent] = useState('');
  const [campaignId, setCampaignId] = useState<number | null>(null);

  const { data: templates = [], isLoading: loadingTemplates } = useApprovedTemplates();
  const bulkSend = useBulkSend();
  const cancelCampaign = useCancelCampaign();
  const { data: campaign } = useCampaignProgress(campaignId);

  const recipientCount = selectAll ? matchingTotal : selected.length;
  const chosen = templates.find((t) => String(t.id) === templateId);

  const handleSend = () => {
    if (!templateId) return;
    bulkSend.mutate(
      {
        template_id: Number(templateId),
        content: content || undefined,
        title: chosen?.name ?? undefined,
        select_all: selectAll,
        selected: selectAll ? undefined : selected,
        filters,
      },
      { onSuccess: (c) => setCampaignId(c.id) },
    );
  };

  const reset = () => {
    setCampaignId(null);
    setContent('');
    setTemplateId('');
    bulkSend.reset();
  };

  const done =
    campaign && ['completed', 'cancelled', 'failed'].includes(campaign.status);
  const progressPct =
    campaign && campaign.total > 0
      ? Math.round(((campaign.sent + campaign.failed) / campaign.total) * 100)
      : 0;

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        if (!o) reset();
        onOpenChange(o);
      }}
    >
      <DialogContent className="sm:max-w-[560px]">
        <DialogHeader>
          <DialogTitle>Send WhatsApp campaign</DialogTitle>
          <DialogDescription>
            Sending via Morasalaty to{' '}
            <strong>{recipientCount.toLocaleString()}</strong>{' '}
            {recipientCount === 1 ? 'influencer' : 'influencers'}
            {selectAll
              ? ' — everyone matching the current filters'
              : ' you ticked (this page only)'}
            . One message per influencer, using their best available number.
          </DialogDescription>
        </DialogHeader>

        {!campaignId ? (
          <div className="space-y-4">
            {/* Make the audience scope unmissable before a large blast. */}
            {!selectAll && (
              <div className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-800">
                This sends to the <strong>{selected.length}</strong> influencers you
                ticked on the current page only. To reach everyone matching your
                filters, close this and use{' '}
                <strong>“Select all {matchingTotal.toLocaleString()} matching”</strong>.
              </div>
            )}
            {selectAll && matchingTotal > MAX_RECIPIENTS && (
              <div className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-800">
                {matchingTotal.toLocaleString()} influencers match, but a single
                campaign is capped at <strong>{MAX_RECIPIENTS.toLocaleString()}</strong>{' '}
                recipients — the rest will <strong>not</strong> be messaged. Narrow
                your filters and run several campaigns to cover everyone.
              </div>
            )}

            <div>
              <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
                Approved template{' '}
                {templates.length > 0 && (
                  <span className="font-normal">({templates.length} available)</span>
                )}
              </Label>
              <Select value={templateId} onValueChange={setTemplateId}>
                <SelectTrigger className="h-auto min-h-9 py-1.5">
                  <SelectValue
                    placeholder={
                      loadingTemplates ? 'Loading templates...' : 'Select a template'
                    }
                  />
                </SelectTrigger>
                <SelectContent className="max-h-80">
                  {templates.map((t) => (
                    <SelectItem key={t.id} value={String(t.id)}>
                      <div className="flex flex-col gap-0.5 py-0.5">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">
                            {t.name || t.title || `Template #${t.id}`}
                          </span>
                          <span className="rounded bg-emerald-100 px-1.5 py-px text-[10px] font-medium uppercase text-emerald-700">
                            {t.status ?? 'approved'}
                          </span>
                          {t.language_code && (
                            <span className="rounded bg-muted px-1.5 py-px text-[10px] uppercase text-muted-foreground">
                              {t.language_code}
                            </span>
                          )}
                        </div>
                        {t.body_text && (
                          <span className="line-clamp-1 max-w-[380px] text-xs text-muted-foreground">
                            {t.body_text}
                          </span>
                        )}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="mt-1.5 text-xs text-muted-foreground">
                Only templates approved &amp; published in Morasalaty (and not
                archived) are listed — the server re-checks this on send.
              </p>
              {!loadingTemplates && templates.length === 0 && (
                <p className="mt-1.5 text-xs text-amber-600">
                  No approved templates found. A template must be approved and
                  published in Morasalaty before it can be used.
                </p>
              )}
            </div>

            {chosen && (
              <div className="space-y-2 rounded-md border bg-muted/40 p-3">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="text-sm font-semibold">
                    {chosen.name || chosen.title}
                  </span>
                  <span className="rounded bg-emerald-100 px-1.5 py-px text-[10px] font-medium uppercase text-emerald-700">
                    {chosen.status ?? 'approved'}
                  </span>
                  {chosen.category && (
                    <span className="rounded bg-muted px-1.5 py-px text-[10px] uppercase text-muted-foreground">
                      {chosen.category}
                    </span>
                  )}
                  {chosen.language_code && (
                    <span className="rounded bg-muted px-1.5 py-px text-[10px] uppercase text-muted-foreground">
                      {chosen.language_code}
                    </span>
                  )}
                </div>
                {(chosen.title_ar || chosen.title_en) && (
                  <p className="text-xs text-muted-foreground">
                    {chosen.title_ar || chosen.title_en}
                  </p>
                )}
                {chosen.body_text ? (
                  <p className="whitespace-pre-wrap rounded bg-background p-2 text-sm">
                    {chosen.body_text}
                  </p>
                ) : (
                  <p className="text-xs text-muted-foreground">
                    This template has no stored body text.
                  </p>
                )}
                <p className="text-xs text-muted-foreground">
                  Variables: <strong>{chosen.body_vars_count ?? 0}</strong>
                  {chosen.body_vars_count > 0 &&
                    ' — the value below fills the first variable.'}
                </p>
              </div>
            )}

            <div>
              <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
                Message parameter (optional)
              </Label>
              <Textarea
                rows={3}
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder="Value passed to the template's first variable"
              />
            </div>

            {bulkSend.isError && (
              <p className="text-sm text-destructive">
                {bulkSend.error?.response?.data?.message ??
                  'Failed to queue the campaign.'}
              </p>
            )}
          </div>
        ) : (
          <div className="space-y-3">
            <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
              <div
                className="h-full bg-primary transition-all"
                style={{ width: `${progressPct}%` }}
              />
            </div>
            <div className="flex justify-between text-sm">
              <span>
                Sent <strong>{campaign?.sent ?? 0}</strong> / {campaign?.total ?? 0}
              </span>
              {(campaign?.failed ?? 0) > 0 && (
                <span className="text-destructive">Failed {campaign?.failed}</span>
              )}
            </div>
            <p className="text-xs capitalize text-muted-foreground">
              Status: {campaign?.status ?? 'queued'}
            </p>
            {campaign?.error && (
              <p className="text-sm text-destructive">{campaign.error}</p>
            )}
            <p className="text-xs text-muted-foreground">
              Sending runs in the background — you can safely close this dialog.
            </p>
          </div>
        )}

        <DialogFooter>
          {!campaignId ? (
            <>
              <Button variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button
                onClick={handleSend}
                disabled={!templateId || recipientCount === 0 || bulkSend.isPending}
              >
                {bulkSend.isPending ? 'Queuing...' : `Send to ${recipientCount.toLocaleString()}`}
              </Button>
            </>
          ) : (
            <>
              {!done && (
                <Button
                  variant="outline"
                  onClick={() => campaignId && cancelCampaign.mutate(campaignId)}
                  disabled={cancelCampaign.isPending}
                >
                  Stop sending
                </Button>
              )}
              <Button onClick={() => onOpenChange(false)}>Close</Button>
            </>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
