"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Plus, Trash2, Save, ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Input, Textarea, Label, Select } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

type Any = any;

const STEP_TYPES = [
  { value: "SEND_MESSAGE", label: "Send a message" },
  { value: "SEND_TEMPLATE", label: "Send a template" },
  { value: "ADD_TAG", label: "Add a tag" },
  { value: "WEBHOOK_CALL", label: "Call a webhook" },
] as const;

export function AutomationEditor({
  automation,
  tags,
  contacts,
  templates = [],
}: {
  automation: Any | null;
  tags: Any[];
  contacts?: Any[];
  templates?: Any[];
}) {
  const router = useRouter();
  void contacts;
  const isEdit = !!automation;
  const savedConfig = automation?.triggerConfig ?? {};
  const savedSteps: Any[] = Array.isArray(automation?.steps) ? automation.steps.map((s: any) => ({
    type: s.stepType ?? s.type,
    config: s.stepConfig ?? s.config ?? {}
  })) : [];

  const [name, setName] = useState(automation?.name ?? "");
  const [description, setDescription] = useState(automation?.description ?? "");
  const [enabled, setEnabled] = useState<boolean>(automation?.isActive ?? false);
  const [triggerType, setTriggerType] = useState<string>(automation?.triggerType ?? "INBOUND_MESSAGE");
  const [keyword, setKeyword] = useState<string>(savedConfig.keyword ?? "");
  const [cron, setCron] = useState<string>(savedConfig.cron ?? "0 * * * *");
  const [steps, setSteps] = useState<Any[]>(
    savedSteps.length
      ? savedSteps
      : [{ type: "SEND_MESSAGE", config: { text: "" } }]
  );
  const [saving, setSaving] = useState(false);

  function updateStep(index: number, patch: Any) {
    setSteps((prev) => prev.map((s, i) => (i === index ? { ...s, ...patch } : s)));
  }

  function updateStepConfig(index: number, config: Any) {
    setSteps((prev) =>
      prev.map((s, i) => (i === index ? { ...s, config: { ...s.config, ...config } } : s))
    );
  }

  function setStepType(index: number, type: string) {
    const base: Any = { type };
    if (type === "SEND_MESSAGE") base.config = { text: "" };
    if (type === "SEND_TEMPLATE") base.config = { templateId: "" };
    if (type === "ADD_TAG") base.config = { tagId: "" };
    if (type === "WEBHOOK_CALL") base.config = { url: "" };
    updateStep(index, base);
  }

  async function save() {
    if (!name.trim()) return toast.error("Name is required.");
    setSaving(true);
    const triggerConfig: Any = {};
    if (triggerType === "KEYWORD") {
      if (!keyword.trim()) return toast.error("Enter a keyword for the trigger.");
      triggerConfig.keyword = keyword.trim();
    }
    if (triggerType === "SCHEDULE") triggerConfig.cron = cron.trim();

    const payload = {
      name: name.trim(),
      description: description.trim() || null,
      enabled,
      triggerType,
      triggerConfig,
      steps,
    };

    const res = await fetch(isEdit ? `/api/automations/${automation.id}` : "/api/automations", {
      method: isEdit ? "PATCH" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    const j = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) return toast.error(j.error ?? "Save failed.");
    toast.success("Automation saved.");
    router.push("/automations");
    router.refresh();
  }

  return (
    <div className="mx-auto max-w-3xl space-y-5">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => router.push("/automations")}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-foreground">
              {isEdit ? "Edit automation" : "New automation"}
            </h1>
            <p className="text-sm text-muted-foreground">Choose a trigger and run steps automatically.</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => setEnabled(!enabled)}>
            {enabled ? "Enabled" : "Disabled"}
          </Button>
          <Button onClick={save} loading={saving}>
            <Save className="h-4 w-4" /> Save
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Details</CardTitle>
        </CardHeader>
        <CardBody className="space-y-4">
          <div>
            <Label>Name</Label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Reply on price quote" />
          </div>
          <div>
            <Label>Description</Label>
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={2}
              placeholder="Optional notes"
            />
          </div>
          <div>
            <Label>Trigger</Label>
            <Select value={triggerType} onChange={(e) => setTriggerType(e.target.value)}>
              <option value="INBOUND_MESSAGE">Every inbound message</option>
              <option value="KEYWORD">Keyword match</option>
              <option value="NEW_CONTACT">New contact</option>
              <option value="ORDER_RECEIVED">Order received</option>
              <option value="SCHEDULE">Schedule</option>
              <option value="INCOMING_WEBHOOK">Incoming webhook event</option>
            </Select>
          </div>
          {triggerType === "KEYWORD" && (
            <div>
              <Label>Keyword (case-insensitive, substring match)</Label>
              <Input value={keyword} onChange={(e) => setKeyword(e.target.value)} placeholder="e.g. price" />
            </div>
          )}
          {triggerType === "INCOMING_WEBHOOK" && (
            <div>
              <Label>Webhook URL</Label>
              <Input 
                readOnly 
                value={isEdit ? `${typeof window !== "undefined" ? window.location.origin : ""}/api/webhooks/automation/${automation.id}` : "Will be generated after saving"} 
              />
              <p className="mt-1 text-xs text-muted-foreground">
                Send a POST request to this URL to trigger this automation. You can pass {"{\"phone\": \"...\"}"} in the JSON body.
              </p>
            </div>
          )}
          {triggerType === "SCHEDULE" && (
            <div>
              <Label>Cron expression</Label>
              <Input value={cron} onChange={(e) => setCron(e.target.value)} placeholder="0 * * * *" />
            </div>
          )}
        </CardBody>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>Steps</CardTitle>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setSteps((s) => [...s, { type: "SEND_MESSAGE", config: { text: "" } }])}
          >
            <Plus className="h-4 w-4" /> Add step
          </Button>
        </CardHeader>
        <CardBody className="space-y-3">
          {steps.map((step, i) => (
            <div key={i} className="rounded-lg border border-border p-4">
              <div className="mb-3 flex items-center gap-2">
                <Badge tone="indigo">Step {i + 1}</Badge>
                <Select
                  value={step.type}
                  onChange={(e) => setStepType(i, e.target.value)}
                  className="h-9 max-w-xs"
                >
                  {STEP_TYPES.map((t) => (
                    <option key={t.value} value={t.value}>
                      {t.label}
                    </option>
                  ))}
                </Select>
                <div className="ml-auto">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-muted-foreground hover:text-red-600"
                    onClick={() => setSteps((s) => s.filter((_, j) => j !== i))}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>

              {step.type === "SEND_MESSAGE" && (
                <div>
                  <Label>
                    Message text{" "}
                    <span className="font-normal text-muted-foreground">
                      (use {"{{name}}"}, {"{{phone}}"}, {"{{message}}"} placeholders)
                    </span>
                  </Label>
                  <Textarea
                    value={step.config?.text ?? ""}
                    onChange={(e) => updateStepConfig(i, { text: e.target.value })}
                    rows={2}
                    placeholder="Hi {{name}}! Thanks for your message."
                  />
                </div>
              )}
              {step.type === "SEND_TEMPLATE" && (
                <div>
                  <Label>WhatsApp Template</Label>
                  <Select
                    value={step.config?.templateId ?? ""}
                    onChange={(e) => updateStepConfig(i, { templateId: e.target.value })}
                  >
                    <option value="">Select a template…</option>
                    {templates.map((t) => (
                      <option key={t.id} value={t.id}>
                        {t.name} ({t.language})
                      </option>
                    ))}
                  </Select>
                </div>
              )}
              {step.type === "ADD_TAG" && (
                <div>
                  <Label>Tag</Label>
                  <Select
                    value={step.config?.tagId ?? ""}
                    onChange={(e) => updateStepConfig(i, { tagId: e.target.value })}
                  >
                    <option value="">Select a tag…</option>
                    {tags.map((t) => (
                      <option key={t.id} value={t.id}>
                        {t.name}
                      </option>
                    ))}
                  </Select>
                </div>
              )}
              {step.type === "WEBHOOK_CALL" && (
                <div>
                  <Label>Webhook URL</Label>
                  <Input
                    value={step.config?.url ?? ""}
                    onChange={(e) => updateStepConfig(i, { url: e.target.value })}
                    placeholder="https://example.com/hooks/whatsapp"
                  />
                </div>
              )}
            </div>
          ))}
        </CardBody>
      </Card>

      {isEdit && Array.isArray(automation.runs) && automation.runs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Recent runs</CardTitle>
          </CardHeader>
          <CardBody>
            <div className="space-y-2">
              {automation.runs.slice(0, 10).map((r: Any) => (
                <div key={r.id} className="flex items-center gap-3 text-sm">
                  <Badge
                    tone={r.status === "COMPLETED" ? "green" : r.status === "RUNNING" ? "blue" : "red"}
                  >
                    {r.status}
                  </Badge>
                  <span className="truncate font-mono text-xs text-muted-foreground">
                    {new Date(r.startedAt).toLocaleString()}
                  </span>
                </div>
              ))}
            </div>
          </CardBody>
        </Card>
      )}
    </div>
  );
}
