import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, type EntityType } from "../api";
import { useAuth } from "../context/AuthContext";
import { formatMoney, formatGainLoss } from "../format";

interface EntityRow {
  id: number;
  name: string;
  type: string;
  vintage_year: number | null;
  fund_size_cents: number | null;
  status: string;
  investedCents: number;
  lastValueCents: number;
}

const TYPE_LABELS: Record<string, string> = {
  fund: "Fund",
  spv: "SPV",
  gp: "GP",
  mgmt_co: "Mgmt Co",
};

const WRITER_ROLES = ["fund_admin", "cfo", "approver"];

export default function EntitiesList() {
  const { user } = useAuth();
  const [entities, setEntities] = useState<EntityRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);

  const isWriter = user && WRITER_ROLES.includes(user.role);

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

  async function loadData() {
    setLoading(true);
    try {
      const rollup = await api.listEntityRollup();
      setEntities(
        rollup.map((r) => ({
          id: r.id,
          name: r.name,
          type: r.type,
          vintage_year: r.vintage_year,
          fund_size_cents: r.fund_size_cents,
          status: r.status,
          investedCents: r.invested_cents,
          lastValueCents: r.last_signed_value_cents,
        })),
      );
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return <div className="text-gray-500 text-sm">Loading...</div>;
  }

  const funds = entities.filter((e) => e.type === "fund" || e.type === "spv");
  const gps = entities.filter((e) => e.type === "gp" || e.type === "mgmt_co");

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-gray-900">Entities</h1>
        {isWriter && (
          <button
            onClick={() => setShowForm(true)}
            className="px-4 py-2 bg-gray-900 text-white text-sm rounded hover:bg-gray-800"
          >
            Add Entity
          </button>
        )}
      </div>

      {showForm && (
        <AddEntityForm
          onClose={() => setShowForm(false)}
          onCreated={() => {
            setShowForm(false);
            loadData();
          }}
        />
      )}

      <EntityTable title="Funds and SPVs" rows={funds} />
      <EntityTable title="GP Entities and Management Companies" rows={gps} />
    </div>
  );
}

function AddEntityForm({
  onClose,
  onCreated,
}: {
  onClose: () => void;
  onCreated: () => void;
}) {
  const [name, setName] = useState("");
  const [type, setType] = useState<EntityType>("fund");
  const [vintageYear, setVintageYear] = useState("");
  const [fundSizeDollars, setFundSizeDollars] = useState("");
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!name.trim()) {
      setError("Name is required.");
      return;
    }
    setError("");
    setSaving(true);
    try {
      const data: any = { name: name.trim(), type };
      if (vintageYear) {
        const vy = parseInt(vintageYear);
        if (isNaN(vy)) {
          setError("Vintage year must be a number.");
          setSaving(false);
          return;
        }
        data.vintage_year = vy;
      }
      if (fundSizeDollars) {
        const dollars = parseFloat(fundSizeDollars.replace(/[,$]/g, ""));
        if (isNaN(dollars)) {
          setError("Fund size must be a number.");
          setSaving(false);
          return;
        }
        data.fund_size_cents = Math.round(dollars * 100);
      }
      await api.createEntity(data);
      onCreated();
    } catch (err: any) {
      setError(err.message || "Failed to create entity");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-6 max-w-lg">
      <h3 className="text-sm font-medium text-gray-900 mb-4">New Entity</h3>
      <form onSubmit={handleSubmit} className="space-y-3">
        <div>
          <label className="block text-sm text-gray-700 mb-1">Name</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent"
            placeholder="Low Time Preference Fund I, LLC"
            required
          />
        </div>
        <div>
          <label className="block text-sm text-gray-700 mb-1">Type</label>
          <select
            value={type}
            onChange={(e) => setType(e.target.value as EntityType)}
            className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
          >
            <option value="fund">Fund</option>
            <option value="spv">SPV</option>
            <option value="gp">GP</option>
            <option value="mgmt_co">Mgmt Co</option>
          </select>
        </div>
        <div className="flex gap-3">
          <div className="flex-1">
            <label className="block text-sm text-gray-700 mb-1">Vintage Year</label>
            <input
              type="text"
              value={vintageYear}
              onChange={(e) => setVintageYear(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
              placeholder="2021"
            />
          </div>
          <div className="flex-1">
            <label className="block text-sm text-gray-700 mb-1">Fund Size ($)</label>
            <input
              type="text"
              value={fundSizeDollars}
              onChange={(e) => setFundSizeDollars(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
              placeholder="3,300,000"
            />
          </div>
        </div>
        {error && (
          <p className="text-sm text-red-600">{error}</p>
        )}
        <div className="flex gap-2 pt-1">
          <button
            type="submit"
            disabled={saving}
            className="px-4 py-2 bg-gray-900 text-white text-sm rounded hover:bg-gray-800 disabled:opacity-50"
          >
            {saving ? "Creating..." : "Create"}
          </button>
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 text-sm rounded hover:bg-gray-50"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}

function EntityTable({ title, rows }: { title: string; rows: EntityRow[] }) {
  const totalInvested = rows.reduce((s, r) => s + r.investedCents, 0);
  const totalValue = rows.reduce((s, r) => s + r.lastValueCents, 0);
  const totalGain = totalValue - totalInvested;

  return (
    <div>
      <h2 className="text-lg font-semibold text-gray-900 mb-3">{title}</h2>
      <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="text-left px-4 py-3 font-medium text-gray-600">Name</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Type</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Vintage</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Invested</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Last Signed Value</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Gain/Loss</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => {
              const gl = formatGainLoss(row.lastValueCents, row.investedCents);
              return (
                <tr key={row.id} className="border-b border-gray-100 hover:bg-gray-50">
                  <td className="px-4 py-3">
                    <Link
                      to={`/entities/${row.id}`}
                      className="text-gray-900 font-medium hover:text-orange-600"
                    >
                      {row.name}
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <span className="inline-block px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">
                      {TYPE_LABELS[row.type] || row.type}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-600">{row.vintage_year || "—"}</td>
                  <td className="px-4 py-3 text-right text-gray-900">{formatMoney(row.investedCents)}</td>
                  <td className="px-4 py-3 text-right text-gray-900">{formatMoney(row.lastValueCents)}</td>
                  <td className={`px-4 py-3 text-right font-medium ${gl.positive ? "text-green-600" : "text-red-600"}`}>
                    {gl.positive ? "+" : "-"}{gl.text}
                  </td>
                </tr>
              );
            })}
            {rows.length > 0 && (
              <tr className="bg-gray-50 font-medium">
                <td className="px-4 py-3 text-gray-900" colSpan={3}>
                  Total
                </td>
                <td className="px-4 py-3 text-right text-gray-900">{formatMoney(totalInvested)}</td>
                <td className="px-4 py-3 text-right text-gray-900">{formatMoney(totalValue)}</td>
                <td className={`px-4 py-3 text-right ${totalGain >= 0 ? "text-green-600" : "text-red-600"}`}>
                  {totalGain >= 0 ? "+" : "-"}{formatMoney(Math.abs(totalGain))}
                </td>
              </tr>
            )}
            {rows.length === 0 && (
              <tr>
                <td className="px-4 py-6 text-center text-gray-400" colSpan={6}>
                  No entities yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
