"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { PlusCircle, CheckCircle, AlertTriangle } from "lucide-react";

const providerOptions = [
  { value: "openai", label: "OpenAI" },
  { value: "anthropic", label: "Anthropic" },
  { value: "google", label: "Google AI" },
  { value: "aws", label: "AWS Bedrock" },
  { value: "azure", label: "Azure" },
  { value: "other", label: "Other" },
];

const categoryOptions = [
  { value: "api", label: "API Usage" },
  { value: "subscription", label: "Subscription" },
  { value: "other", label: "Other" },
];

function getCurrentMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}

export default function AddEntryPage() {
  const router = useRouter();
  const [provider, setProvider] = useState("openai");
  const [amount, setAmount] = useState("");
  const [period, setPeriod] = useState(getCurrentMonth());
  const [category, setCategory] = useState("api");
  const [note, setNote] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});

  function validate(): boolean {
    const errs: Record<string, string> = {};
    if (!provider) errs.provider = "Provider is required";
    if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) {
      errs.amount = "Enter a valid amount greater than $0";
    }
    if (!period) errs.period = "Period is required";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!validate()) return;

    setSubmitting(true);
    setError("");

    try {
      const res = await fetch("/api/costs", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          provider,
          amount: Number(amount),
          period,
          category,
          note: note.trim() || null,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Failed to add entry");
        return;
      }

      setSubmitted(true);
      setTimeout(() => {
        setSubmitted(false);
        setAmount("");
        setNote("");
        router.push("/dashboard/spending");
      }, 1500);
    } catch {
      setError("Failed to add entry");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-gray-100">Add Cost Entry</h1>
        <p className="mt-1 text-sm text-gray-400">
          Log a new AI cloud spending entry
        </p>
      </div>

      {error && (
        <div className="mx-auto max-w-2xl flex items-center gap-2 rounded-lg border border-red-800/50 bg-red-900/20 px-4 py-3 text-sm text-red-400">
          <AlertTriangle size={16} />
          {error}
          <button
            onClick={() => setError("")}
            className="ml-auto text-red-400 hover:text-red-300"
          >
            Dismiss
          </button>
        </div>
      )}

      <Card className="mx-auto max-w-2xl">
        {submitted ? (
          <div className="flex flex-col items-center gap-4 py-8">
            <CheckCircle className="h-12 w-12 text-emerald-400" />
            <p className="text-lg font-medium text-gray-100">Entry Added</p>
            <p className="text-sm text-gray-400">
              Redirecting to spending page...
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-6">
            <Select
              id="provider"
              label="Provider"
              options={providerOptions}
              value={provider}
              onChange={(e) => setProvider(e.target.value)}
              error={errors.provider}
            />

            <Input
              id="amount"
              label="Amount (USD)"
              type="number"
              step="0.01"
              min="0"
              placeholder="0.00"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              error={errors.amount}
            />

            <Input
              id="period"
              label="Period"
              type="month"
              value={period}
              onChange={(e) => setPeriod(e.target.value)}
              error={errors.period}
            />

            <Select
              id="category"
              label="Category"
              options={categoryOptions}
              value={category}
              onChange={(e) => setCategory(e.target.value)}
            />

            <Input
              id="note"
              label="Note (optional)"
              placeholder="e.g., GPT-4o production traffic"
              value={note}
              onChange={(e) => setNote(e.target.value)}
            />

            <Button
              type="submit"
              size="lg"
              className="w-full"
              disabled={submitting}
            >
              <PlusCircle size={18} />
              {submitting ? "Adding..." : "Add Entry"}
            </Button>
          </form>
        )}
      </Card>
    </div>
  );
}
