"use client";

import { useEffect, useState } from "react";
import { transporterApi, type TransporterBelt } from "@/lib/api/transporter";
import { addressLookupApi } from "@/lib/api/addressLookup";
import { ApiException } from "@/lib/api/client";
import { useToken } from "@/lib/auth/useToken";
import Loader from "@/components/ui/Loader";
import ConfirmDialog from "@/components/ui/ConfirmDialog";
import { Trash2, Plus } from "lucide-react";

type DraftEntry = { city: string; min_price: string; max_price: string };

export default function TransporterBeltsPage() {
  const { token, ready } = useToken();
  const [belts, setBelts] = useState<TransporterBelt[]>([]);
  const [loading, setLoading] = useState(true);
  const [states, setStates] = useState<string[]>([]);
  const [cities, setCities] = useState<string[]>([]);
  const [selectedState, setSelectedState] = useState("");
  const [loadingAddress, setLoadingAddress] = useState("");
  const [entries, setEntries] = useState<DraftEntry[]>([]);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [pendingDeleteId, setPendingDeleteId] = useState<number | null>(null);

  const loadBelts = (t: string) => transporterApi.belts(t).then((r) => setBelts(r.data));

  useEffect(() => {
    if (!ready || !token) return;
    Promise.all([loadBelts(token), addressLookupApi.states().then(setStates).catch(() => setStates([]))]).finally(
      () => setLoading(false)
    );
  }, [ready, token]);

  const onStateChange = async (state: string) => {
    setSelectedState(state);
    setCities([]);
    if (!state) return;
    try {
      const list = await addressLookupApi.cities(state);
      setCities(list);
    } catch {
      setCities([]);
    }
  };

  const addCity = (city: string) => {
    if (!city || entries.some((e) => e.city === city)) return;
    setEntries((prev) => [...prev, { city, min_price: "", max_price: "" }]);
  };

  const updateEntry = (idx: number, key: keyof DraftEntry, value: string) =>
    setEntries((prev) => prev.map((e, i) => (i === idx ? { ...e, [key]: value } : e)));

  const removeEntry = (idx: number) => setEntries((prev) => prev.filter((_, i) => i !== idx));

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token) return;
    setError(null);
    setMsg(null);
    if (!loadingAddress.trim()) return setError("Loading address is required.");
    if (entries.length === 0) return setError("Add at least one unloading city.");
    for (const en of entries) {
      if (!en.min_price || !en.max_price) return setError(`Enter min and max price for ${en.city}.`);
      if (Number(en.max_price) < Number(en.min_price))
        return setError(`Max price must be ≥ min price for ${en.city}.`);
    }

    setSaving(true);
    try {
      const r = await transporterApi.storeBelt(token, {
        loading_address: loadingAddress,
        entries: entries.map((en) => ({
          city: en.city,
          min_price: Number(en.min_price),
          max_price: Number(en.max_price),
        })),
      });
      setMsg(r.message);
      setLoadingAddress("");
      setEntries([]);
      setSelectedState("");
      setCities([]);
      await loadBelts(token);
    } catch (err) {
      setError(err instanceof ApiException ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const removeRow = async (id?: number) => {
    if (!token || !id) return;
    try {
      await transporterApi.deleteBeltEntry(token, id);
      setPendingDeleteId(null);
      await loadBelts(token);
    } catch (err) {
      setError(err instanceof ApiException ? err.message : "Remove failed");
    }
  };

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-10 shadow-sm ring-1 ring-gray-100">
        <Loader label="Loading belts…" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-semibold text-gray-900">My Belts</h1>
        <p className="text-sm text-gray-600">Define loading point and unloading cities with price range.</p>
      </div>

      <form onSubmit={submit} className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
        <h3 className="text-sm font-semibold text-gray-900">Add new belt</h3>
        <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
          <div className="md:col-span-3">
            <label className="mb-1 block text-xs font-medium text-gray-700">Loading address</label>
            <input
              value={loadingAddress}
              onChange={(e) => setLoadingAddress(e.target.value)}
              placeholder="e.g. Bhilwara, Rajasthan"
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414]"
            />
          </div>
          <div>
            <label className="mb-1 block text-xs font-medium text-gray-700">Unloading state</label>
            <select
              value={selectedState}
              onChange={(e) => onStateChange(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414]"
            >
              <option value="">Select state</option>
              {states.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </div>
          <div className="md:col-span-2">
            <label className="mb-1 block text-xs font-medium text-gray-700">Add city</label>
            <select
              value=""
              onChange={(e) => {
                addCity(e.target.value);
                e.target.value = "";
              }}
              disabled={!selectedState}
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414] disabled:bg-gray-50"
            >
              <option value="">{selectedState ? "Select city" : "Choose state first"}</option>
              {cities.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </select>
          </div>
        </div>

        {entries.length > 0 && (
          <div className="overflow-x-auto rounded-lg ring-1 ring-gray-100">
            <table className="w-full min-w-[640px] divide-y divide-gray-100 text-sm">
              <thead className="bg-gray-50 text-xs uppercase text-gray-500">
                <tr>
                  <th className="px-3 py-2 text-left">City</th>
                  <th className="px-3 py-2 text-left">Min ₹</th>
                  <th className="px-3 py-2 text-left">Max ₹</th>
                  <th className="px-3 py-2"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {entries.map((en, i) => (
                  <tr key={en.city}>
                    <td className="px-3 py-2 font-medium text-gray-800">{en.city}</td>
                    <td className="px-3 py-2">
                      <input
                        type="number"
                        min="0"
                        value={en.min_price}
                        placeholder="Min amount"
                        onChange={(e) => updateEntry(i, "min_price", e.target.value)}
                        className="w-28 rounded-lg border border-gray-200 px-2 py-2 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414]"
                      />
                    </td>
                    <td className="px-3 py-2">
                      <input
                        type="number"
                        min="0"
                        value={en.max_price}
                        placeholder="Max amount"
                        onChange={(e) => updateEntry(i, "max_price", e.target.value)}
                        className="w-28 rounded-lg border border-gray-200 px-2 py-2 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414]"
                      />
                    </td>
                    <td className="px-3 py-2 text-right">
                      <button
                        type="button"
                        onClick={() => removeEntry(i)}
                        className="rounded p-2 text-gray-400 hover:text-red-600"
                        aria-label="Remove"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {error && <p className="text-sm text-red-600">{error}</p>}
        {msg && <p className="text-sm text-emerald-700">{msg}</p>}

        <div className="flex justify-end">
          <button
            type="submit"
            disabled={saving}
            className="inline-flex items-center gap-2 rounded-lg bg-[#CC1414] px-5 py-2 text-sm font-medium text-white hover:bg-[#b21010] disabled:opacity-60"
          >
            <Plus className="h-4 w-4" />
            {saving ? "Saving…" : "Save belt"}
          </button>
        </div>
      </form>

      <div className="space-y-3">
        <h3 className="text-sm font-semibold text-gray-900">Saved belts</h3>
        {belts.length === 0 ? (
          <div className="rounded-xl bg-white p-8 text-center text-sm text-gray-600 shadow-sm ring-1 ring-gray-100">
            No belts saved yet.
          </div>
        ) : (
          belts.map((b, idx) => (
            <div key={`${b.loading_address}-${idx}`} className="rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-100">
              <div className="mb-2 text-sm font-semibold text-gray-900">
                Loading: <span className="text-[#CC1414]">{b.loading_address}</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full min-w-[640px] divide-y divide-gray-100 text-sm">
                  <thead className="bg-gray-50 text-xs uppercase text-gray-500">
                    <tr>
                      <th className="px-3 py-2 text-left">State</th>
                      <th className="px-3 py-2 text-left">City</th>
                      <th className="px-3 py-2 text-left">Min ₹</th>
                      <th className="px-3 py-2 text-left">Max ₹</th>
                      <th className="px-3 py-2"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {b.unloading_address.map((u) => (
                      <tr key={u.id ?? `${u.state}-${u.city}`}>
                        <td className="px-3 py-2">{u.state}</td>
                        <td className="px-3 py-2 font-medium text-gray-800">{u.city}</td>
                        <td className="px-3 py-2">₹{u.min_price ?? "—"}</td>
                        <td className="px-3 py-2">₹{u.max_price ?? "—"}</td>
                        <td className="px-3 py-2 text-right">
                          <button
                            type="button"
                            onClick={() => setPendingDeleteId(u.id ?? null)}
                            className="rounded p-2 text-gray-400 hover:text-red-600"
                            aria-label="Remove"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ))
        )}
      </div>

      <ConfirmDialog
        open={pendingDeleteId !== null}
        title="Delete this belt entry?"
        description="This unloading route entry will be removed permanently."
        confirmLabel="Delete"
        onCancel={() => setPendingDeleteId(null)}
        onConfirm={() => {
          if (pendingDeleteId !== null) removeRow(pendingDeleteId);
        }}
      />
    </div>
  );
}
