"use client";

import { useCallback, useEffect, useState } from "react";
import { Button, Card, Label } from "@/components/ui";
import {
  Database,
  ExternalLink,
  Loader2,
  Copy,
  Eye,
  EyeOff,
  CheckCircle,
  AlertCircle,
  Trash2,
} from "lucide-react";

type OdooInstance = {
  id: number;
  db_name: string;
  odoo_url: string;
  login: string;
  password: string | null;
  mode: "template" | "empty";
  status: "CREATING" | "RUNNING" | "ERROR";
  last_error?: string | null;
  created_at?: string;
};

export default function OdooContent() {
  const [instance, setInstance] = useState<OdooInstance | null>(null);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [mode, setMode] = useState<"template" | "empty">("template");
  const [error, setError] = useState("");
  const [showPwd, setShowPwd] = useState(false);
  const [copied, setCopied] = useState("");

  const load = useCallback(async () => {
    const res = await fetch("/api/odoo");
    const b = await res.json().catch(() => ({}));
    setInstance(b.instance || null);
    setLoading(false);
    return b.instance as OdooInstance | null;
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  // Poll while a provision is in progress.
  useEffect(() => {
    if (instance?.status !== "CREATING") return;
    const t = setInterval(async () => {
      const i = await load();
      if (i && i.status !== "CREATING") clearInterval(t);
    }, 4000);
    return () => clearInterval(t);
  }, [instance?.status, load]);

  async function create() {
    setCreating(true);
    setError("");
    const res = await fetch("/api/odoo", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ mode }),
    });
    const b = await res.json().catch(() => ({}));
    setCreating(false);
    if (!res.ok) {
      setError(b.error || "Failed to create Odoo system.");
      return;
    }
    setInstance(b.instance);
  }

  async function remove() {
    if (!confirm("Delete your Odoo database? This cannot be undone.")) return;
    await fetch("/api/odoo", { method: "DELETE" });
    setInstance(null);
  }

  async function copy(label: string, value: string) {
    await navigator.clipboard.writeText(value);
    setCopied(label);
    setTimeout(() => setCopied(""), 1500);
  }

  if (loading) {
    return (
      <div className="flex items-center gap-2 text-slate-500">
        <Loader2 size={18} className="animate-spin" /> Loading...
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-2xl">
      <div className="mb-6 flex items-center gap-3">
        <span className="flex h-11 w-11 items-center justify-center rounded-lg bg-brand/10 text-brand">
          <Database size={22} />
        </span>
        <div>
          <h1 className="text-2xl font-bold text-ink">Odoo ERP</h1>
          <p className="text-sm text-slate-500">Your own Odoo system — your AI agent works directly on it.</p>
        </div>
      </div>

      {!instance && (
        <Card className="grid gap-4">
          <p className="text-sm text-slate-600">
            Create a private Odoo database (named after your account). You can create <strong>one</strong> system.
          </p>
          <div>
            <Label htmlFor="mode">Choose a starting point</Label>
            <select
              id="mode"
              value={mode}
              onChange={(e) => setMode(e.target.value as "template" | "empty")}
              className="mt-1 w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm text-ink focus:border-brand focus:outline-none"
            >
              <option value="template">Ready-made template (recommended)</option>
              <option value="empty">Empty database</option>
            </select>
          </div>
          {error && (
            <div className="flex items-center gap-2 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">
              <AlertCircle size={16} /> {error}
            </div>
          )}
          <Button onClick={create} disabled={creating}>
            {creating ? <Loader2 size={16} className="animate-spin" /> : <Database size={16} />}
            {creating ? "Creating..." : "Create my Odoo system"}
          </Button>
        </Card>
      )}

      {instance?.status === "CREATING" && (
        <Card className="flex items-center gap-3">
          <Loader2 size={20} className="animate-spin text-brand" />
          <div>
            <p className="font-semibold text-ink">Provisioning &quot;{instance.db_name}&quot;…</p>
            <p className="text-sm text-slate-500">This can take up to a couple of minutes. The page updates automatically.</p>
          </div>
        </Card>
      )}

      {instance?.status === "ERROR" && (
        <Card className="grid gap-4">
          <div className="flex items-start gap-2 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">
            <AlertCircle size={16} className="mt-0.5" />
            <span>{instance.last_error || "Provisioning failed."}</span>
          </div>
          <Button onClick={remove} className="bg-red-600 hover:bg-red-700">
            <Trash2 size={16} /> Remove and retry
          </Button>
        </Card>
      )}

      {instance?.status === "RUNNING" && (
        <Card className="grid gap-4">
          <div className="flex items-center gap-2 text-emerald-700">
            <CheckCircle size={18} /> <span className="font-semibold">Your Odoo system is ready</span>
          </div>

          <a
            href={instance.odoo_url}
            target="_blank"
            className="inline-flex items-center gap-1 text-sm font-semibold text-brand hover:underline"
          >
            {instance.odoo_url} <ExternalLink size={14} />
          </a>

          <div className="grid gap-3 rounded-lg border border-slate-200 p-4">
            <Field label="Database" value={instance.db_name} onCopy={() => copy("db", instance.db_name)} copied={copied === "db"} />
            <Field label="Login" value={instance.login} onCopy={() => copy("login", instance.login)} copied={copied === "login"} />
            {instance.password && (
              <div className="grid gap-1">
                <span className="text-xs font-semibold uppercase tracking-wide text-slate-400">Password</span>
                <div className="flex items-center gap-2">
                  <code className="flex-1 truncate rounded bg-slate-50 px-2 py-1 text-sm">
                    {showPwd ? instance.password : "•".repeat(16)}
                  </code>
                  <button onClick={() => setShowPwd((s) => !s)} className="text-slate-500 hover:text-ink">
                    {showPwd ? <EyeOff size={16} /> : <Eye size={16} />}
                  </button>
                  <button onClick={() => copy("pwd", instance.password!)} className="text-slate-500 hover:text-ink">
                    <Copy size={16} />
                  </button>
                  {copied === "pwd" && <span className="text-xs text-emerald-600">copied</span>}
                </div>
              </div>
            )}
          </div>

          <p className="text-xs text-slate-500">
            These credentials are shared with your AI agent so it can read and update your Odoo data.
          </p>

          <Button onClick={remove} className="w-fit bg-red-600 hover:bg-red-700">
            <Trash2 size={16} /> Delete Odoo system
          </Button>
        </Card>
      )}
    </div>
  );
}

function Field({ label, value, onCopy, copied }: { label: string; value: string; onCopy: () => void; copied: boolean }) {
  return (
    <div className="grid gap-1">
      <span className="text-xs font-semibold uppercase tracking-wide text-slate-400">{label}</span>
      <div className="flex items-center gap-2">
        <code className="flex-1 truncate rounded bg-slate-50 px-2 py-1 text-sm">{value}</code>
        <button onClick={onCopy} className="text-slate-500 hover:text-ink">
          <Copy size={16} />
        </button>
        {copied && <span className="text-xs text-emerald-600">copied</span>}
      </div>
    </div>
  );
}
