"use client";

import { useState } from "react";
import { Loader2, Mail, Bell, TriangleAlert, Car } from "lucide-react";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import { Button } from "@/presentation/components/ui/button";
import { Checkbox } from "@/presentation/components/ui/checkbox";
import { Label } from "@/presentation/components/ui/label";
import { Textarea } from "@/presentation/components/ui/textarea";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import type { ComplianceAlertChannel, ComplianceAlertPreview } from "@/domain/entities/compliance";

export type ComplianceAlertTarget =
  | { kind: "vehicle"; id: number; label: string }
  | { kind: "company"; id: number; label: string };

interface ComplianceAlertDialogProps {
  target: ComplianceAlertTarget | null;
  onClose: () => void;
  onSent: () => void;
}

export function ComplianceAlertDialog({ target, onClose, onSent }: ComplianceAlertDialogProps) {
  const t = useT();
  const { complianceRepository } = useRepositories();

  const { data: preview, loading } = useApiQuery(
    () =>
      target!.kind === "vehicle"
        ? complianceRepository.getVehicleAlertPreview(target!.id)
        : complianceRepository.getCompanyAlertPreview(target!.id),
    { enabled: target !== null, deps: [target?.kind, target?.id] },
  );

  return (
    <Dialog open={target !== null} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {target?.kind === "company"
              ? t.compliance.alertDialog.companyTitle(target.label)
              : t.compliance.alertDialog.vehicleTitle(target?.label ?? "")}
          </DialogTitle>
          <DialogDescription>{t.compliance.alertDialog.description}</DialogDescription>
        </DialogHeader>

        {loading || !preview || !target ? (
          <div className="space-y-3">
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-8 w-full" />
            <Skeleton className="h-64 w-full" />
          </div>
        ) : (
          // Keyed by the preview so a new target starts from its own generated message.
          <AlertForm key={`${target.kind}-${target.id}-${preview.subject}`} target={target} preview={preview} onClose={onClose} onSent={onSent} />
        )}
      </DialogContent>
    </Dialog>
  );
}

function AlertForm({
  target,
  preview,
  onClose,
  onSent,
}: {
  target: ComplianceAlertTarget;
  preview: ComplianceAlertPreview;
  onClose: () => void;
  onSent: () => void;
}) {
  const t = useT();
  const locale = useLocale();
  const { complianceRepository } = useRepositories();
  const [channels, setChannels] = useState<ComplianceAlertChannel[]>(["email", "in_app"]);
  const [body, setBody] = useState(preview.body);
  const [force, setForce] = useState(false);

  const send = useApiMutation(
    () => {
      const payload = {
        channels,
        message_override: body !== preview.body ? body : undefined,
        force: force || undefined,
      };
      return target.kind === "vehicle"
        ? complianceRepository.sendVehicleAlert(target.id, payload)
        : complianceRepository.sendCompanyAlert(target.id, payload);
    },
    {
      successMessage: t.compliance.alertDialog.sent,
      onSuccess: () => {
        onSent();
        onClose();
      },
    },
  );

  const toggleChannel = (channel: ComplianceAlertChannel, checked: boolean) =>
    setChannels((prev) => (checked ? [...new Set([...prev, channel])] : prev.filter((c) => c !== channel)));

  // The API only sets next_allowed_at while the rate limit is running.
  const rateLimited = !!preview.next_allowed_at;
  const canSend = channels.length > 0 && (!rateLimited || force) && !send.loading;

  return (
    <>
      <div className="space-y-4">
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-[1fr_auto]">
          <div>
            <div className="text-xs font-semibold text-muted-foreground">{t.compliance.alertDialog.recipients}</div>
            <div className="mt-1 flex flex-wrap gap-1.5">
              {preview.recipients.map((r) => (
                <span key={r.email} className="rounded-md border border-border bg-muted/50 px-2 py-0.5 text-xs">
                  {r.name} &lt;{r.email}&gt;
                </span>
              ))}
            </div>
          </div>
          <div className="flex items-center gap-1.5 self-end text-xs text-muted-foreground">
            <Car className="h-3.5 w-3.5" />
            {t.compliance.alertDialog.vehiclesCovered(preview.vehicles_count)}
          </div>
        </div>

        <div>
          <div className="text-xs font-semibold text-muted-foreground">{t.compliance.alertDialog.subject}</div>
          <div className="mt-1 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm font-medium">{preview.subject}</div>
        </div>

        <div>
          <Label htmlFor="compliance-alert-body" className="text-xs font-semibold text-muted-foreground">
            {t.compliance.alertDialog.message}
          </Label>
          <Textarea
            id="compliance-alert-body"
            value={body}
            onChange={(e) => setBody(e.target.value)}
            className="mt-1 h-64 font-mono text-xs leading-relaxed"
          />
        </div>

        <div>
          <div className="text-xs font-semibold text-muted-foreground mb-2">{t.compliance.alertDialog.channels}</div>
          <div className="flex flex-wrap gap-4">
            <label className="flex items-center gap-2 text-sm">
              <Checkbox checked={channels.includes("email")} onCheckedChange={(c) => toggleChannel("email", c === true)} />
              <Mail className="h-3.5 w-3.5 text-muted-foreground" />
              {t.compliance.alertDialog.email}
            </label>
            <label className="flex items-center gap-2 text-sm">
              <Checkbox checked={channels.includes("in_app")} onCheckedChange={(c) => toggleChannel("in_app", c === true)} />
              <Bell className="h-3.5 w-3.5 text-muted-foreground" />
              {t.compliance.alertDialog.inApp}
            </label>
          </div>
          {channels.length === 0 && <p className="mt-1 text-xs text-red-600">{t.compliance.alertDialog.noChannel}</p>}
        </div>

        {rateLimited && (
          <div className="flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
            <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
            <div className="flex-1">
              {t.compliance.alertDialog.recentlySent(formatDate(preview.next_allowed_at!, locale))}
              <label className="mt-1.5 flex items-center gap-2 font-medium">
                <Checkbox checked={force} onCheckedChange={(c) => setForce(c === true)} />
                {t.compliance.alertDialog.force}
              </label>
            </div>
          </div>
        )}
      </div>

      <DialogFooter>
        <Button variant="outline" onClick={onClose}>{t.common.cancel}</Button>
        <Button disabled={!canSend} onClick={() => send.mutate(undefined)}>
          {send.loading && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
          {t.compliance.alertDialog.send}
        </Button>
      </DialogFooter>
    </>
  );
}
