"use client";

import { useState, useEffect } from "react";
import ManagePageSkeleton from "@/components/shared/manage-page-skeleton";

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

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

export default function ManageRatesPage() {
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [rateOptions, setRateOptions] = useState<RateOption[]>([]);
  const [rates, setRates] = useState<RateEntry[]>([]);

  useEffect(() => {
    Promise.all([
      fetch("/api/onboarding/options").then((r) => r.json()),
      fetch("/api/profile/rates").then((r) => r.json()),
    ])
      .then(([opts, data]) => {
        const options: RateOption[] = opts.rates || [];
        setRateOptions(options);

        const existingRates: { rate_id: number; in_call: number; out_call: number }[] = (data.rates || []).map(
          (r: { rate_id: number; in_call: number; out_call: number }) => ({
            rate_id: r.rate_id,
            in_call: r.in_call,
            out_call: r.out_call,
          })
        );

        // Build rate entries for all options, filling in existing values
        const entries = options.map((opt) => {
          const existing = existingRates.find((r) => r.rate_id === opt.id);
          return {
            rate_id: opt.id,
            in_call: existing?.in_call || 0,
            out_call: existing?.out_call || 0,
          };
        });
        setRates(entries);
      })
      .finally(() => setLoading(false));
  }, []);

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

  async function handleSave() {
    setSaving(true);
    setMessage(null);
    try {
      const activeRates = rates.filter((r) => r.in_call > 0 || r.out_call > 0);
      const res = await fetch("/api/profile/rates", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rates: activeRates }),
      });
      if (!res.ok) throw new Error("Failed");
      setMessage({ type: "success", text: "Rates updated successfully." });
    } catch {
      setMessage({ type: "error", text: "Failed to update rates." });
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <ManagePageSkeleton />;

  return (
    <div className="max-w-2xl mx-auto">
      <h1 className="text-3xl font-bold text-text mb-6">Manage Rates</h1>

      <div className="bg-surface rounded-lg p-6 space-y-5">
        {message && (
          <div className={`p-3 rounded-lg text-sm ${message.type === "success" ? "bg-green-900/30 text-green-400" : "bg-red-900/30 text-red-400"}`}>
            {message.text}
          </div>
        )}

        <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>
          {rateOptions.map((opt) => {
            const entry = rates.find((r) => r.rate_id === opt.id);
            return (
              <div key={opt.id} className="grid grid-cols-3 gap-4 items-center">
                <span className="text-text text-sm">{opt.name}</span>
                <input
                  type="number"
                  min={0}
                  value={entry?.in_call || 0}
                  onChange={(e) => updateRate(opt.id, "in_call", e.target.value)}
                  placeholder="0"
                  className="bg-background border border-surface-light rounded-lg px-3 py-2 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                />
                <input
                  type="number"
                  min={0}
                  value={entry?.out_call || 0}
                  onChange={(e) => updateRate(opt.id, "out_call", e.target.value)}
                  placeholder="0"
                  className="bg-background border border-surface-light rounded-lg px-3 py-2 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
            );
          })}
        </div>

        <button
          onClick={handleSave}
          disabled={saving}
          className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
        >
          {saving ? "Saving..." : "Save Rates"}
        </button>
      </div>
    </div>
  );
}
