"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useToastStore } from "@/lib/stores/toast-store";

interface RateOption {
  id: number;
  name: string;
}

interface RateEntry {
  rate_id: number;
  name: string;
  in_call: string;
  out_call: string;
}

export default function OnboardingRatesPage() {
  const router = useRouter();
  const addToast = useToastStore((s) => s.addToast);
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [rates, setRates] = useState<RateEntry[]>([]);

  useEffect(() => {
    async function fetchOptions() {
      try {
        const res = await fetch("/api/onboarding/options");
        if (res.ok) {
          const data = await res.json();
          const rateOptions: RateOption[] = data.rates || [];
          setRates(
            rateOptions.map((r) => ({
              rate_id: r.id,
              name: r.name,
              in_call: "",
              out_call: "",
            }))
          );
        }
      } catch {
        console.error("Failed to load options");
      } finally {
        setLoading(false);
      }
    }
    fetchOptions();
  }, []);

  function updateRate(index: number, field: "in_call" | "out_call", value: string) {
    setRates((prev) =>
      prev.map((r, i) => (i === index ? { ...r, [field]: value } : r))
    );
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const filledRates = rates
        .filter((r) => r.in_call || r.out_call)
        .map((r) => ({
          rate_id: r.rate_id,
          in_call: parseInt(r.in_call) || 0,
          out_call: parseInt(r.out_call) || 0,
        }));

      const res = await fetch("/api/onboarding/rates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rates: filledRates }),
      });
      if (!res.ok) throw new Error("Failed to save");
      router.push("/onboarding/services");
    } catch {
      addToast("error", "Failed to save rates.");
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="bg-surface rounded-lg p-6 text-center text-text-muted">
          Loading...
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-8">
        <div className="flex items-center gap-2 text-sm text-text-muted mb-2">
          <span className="bg-primary text-white rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold">4</span>
          <span>Step 4 of 6</span>
        </div>
        <h1 className="text-3xl font-bold text-text">Set Your Rates</h1>
        <p className="text-text-muted mt-1">Set your in-call and out-call rates for each duration.</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-surface rounded-lg p-6 space-y-5">
        <div className="space-y-3">
          <div className="grid grid-cols-3 gap-4 text-sm font-medium text-text-muted">
            <span>Duration</span>
            <span>In-Call</span>
            <span>Out-Call</span>
          </div>
          {rates.map((rate, i) => (
            <div key={rate.rate_id} className="grid grid-cols-3 gap-4 items-center">
              <span className="text-text text-sm">{rate.name}</span>
              <input
                type="number"
                min={0}
                value={rate.in_call}
                onChange={(e) => updateRate(i, "in_call", e.target.value)}
                placeholder="0"
                className="bg-background border border-surface-light rounded-lg px-3 py-2 text-text focus:outline-none focus:ring-2 focus:ring-primary text-sm"
              />
              <input
                type="number"
                min={0}
                value={rate.out_call}
                onChange={(e) => updateRate(i, "out_call", e.target.value)}
                placeholder="0"
                className="bg-background border border-surface-light rounded-lg px-3 py-2 text-text focus:outline-none focus:ring-2 focus:ring-primary text-sm"
              />
            </div>
          ))}
        </div>

        <div className="flex justify-between pt-4">
          <button
            type="button"
            onClick={() => router.push("/onboarding/video")}
            className="text-text-muted hover:text-text transition-colors"
          >
            Back
          </button>
          <button
            type="submit"
            disabled={saving}
            className="bg-primary hover:bg-primary-dark text-white px-8 py-3 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {saving ? "Saving..." : "Next: Services"}
          </button>
        </div>
      </form>
    </div>
  );
}
