"use client";

import { useState } from "react";
import { ConfirmDialog } from "~/components/ui/ConfirmDialog.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { trpc } from "~/lib/trpc/client.js";

type EditingRule = {
  id?: string;
  chapter: string;
  location: string;
  level: string;
  costMultiplier: number;
  billMultiplier: number;
  shoringRatio: string;
  additionalEffortRatio: string;
  description: string;
  sortOrder: number;
};

type EditingSet = {
  id?: string;
  name: string;
  description: string;
  isDefault: boolean;
  rules: EditingRule[];
};

const CHAPTER_PRESETS = [
  "Animation",
  "Compositing",
  "3D Modeling",
  "3D Lighting",
  "3D Rigging",
  "3D Environment",
  "Motion Graphics",
  "Art Direction",
  "Project Management",
];

const LOCATION_PRESETS = [
  "Germany",
  "India",
  "Poland",
  "Romania",
  "Spain",
  "UK",
  "USA",
  "Canada",
];

const LEVEL_PRESETS = [
  "Junior",
  "Mid",
  "Senior",
  "Lead",
  "Principal",
];

const emptyRule: EditingRule = {
  chapter: "",
  location: "",
  level: "",
  costMultiplier: 1.0,
  billMultiplier: 1.0,
  shoringRatio: "",
  additionalEffortRatio: "",
  description: "",
  sortOrder: 0,
};

const emptySet: EditingSet = {
  name: "",
  description: "",
  isDefault: false,
  rules: [],
};

export function ExperienceMultipliersClient() {
  const utils = trpc.useUtils();
  const { data: sets, isLoading } = trpc.experienceMultiplier.list.useQuery();

  const createMutation = trpc.experienceMultiplier.create.useMutation({
    onSuccess: () => {
      utils.experienceMultiplier.list.invalidate();
      setEditing(null);
    },
  });
  const updateMutation = trpc.experienceMultiplier.update.useMutation({
    onSuccess: () => {
      utils.experienceMultiplier.list.invalidate();
      setEditing(null);
    },
  });
  const deleteMutation = trpc.experienceMultiplier.delete.useMutation({
    onSuccess: () => utils.experienceMultiplier.list.invalidate(),
  });

  const [editing, setEditing] = useState<EditingSet | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);

  function handleSave() {
    if (!editing) return;
    const payload = {
      name: editing.name,
      description: editing.description || undefined,
      isDefault: editing.isDefault,
      rules: editing.rules.map((r, i) => ({
        ...(r.chapter ? { chapter: r.chapter } : {}),
        ...(r.location ? { location: r.location } : {}),
        ...(r.level ? { level: r.level } : {}),
        costMultiplier: r.costMultiplier,
        billMultiplier: r.billMultiplier,
        ...(r.shoringRatio !== "" ? { shoringRatio: parseFloat(r.shoringRatio) } : {}),
        ...(r.additionalEffortRatio !== "" ? { additionalEffortRatio: parseFloat(r.additionalEffortRatio) } : {}),
        ...(r.description ? { description: r.description } : {}),
        sortOrder: i,
      })),
    };

    if (editing.id) {
      updateMutation.mutate({ id: editing.id, ...payload });
    } else {
      createMutation.mutate(payload);
    }
  }

  function handleEdit(set: NonNullable<typeof sets>[number]) {
    setEditing({
      id: set.id,
      name: set.name,
      description: set.description ?? "",
      isDefault: set.isDefault,
      rules: set.rules.map((r) => ({
        id: r.id,
        chapter: r.chapter ?? "",
        location: r.location ?? "",
        level: r.level ?? "",
        costMultiplier: r.costMultiplier,
        billMultiplier: r.billMultiplier,
        shoringRatio: r.shoringRatio != null ? String(r.shoringRatio) : "",
        additionalEffortRatio: r.additionalEffortRatio != null ? String(r.additionalEffortRatio) : "",
        description: r.description ?? "",
        sortOrder: r.sortOrder,
      })),
    });
  }

  function addRule() {
    if (!editing) return;
    setEditing({
      ...editing,
      rules: [...editing.rules, { ...emptyRule, sortOrder: editing.rules.length }],
    });
  }

  function removeRule(index: number) {
    if (!editing) return;
    setEditing({
      ...editing,
      rules: editing.rules.filter((_, i) => i !== index),
    });
  }

  function updateRule(index: number, updates: Partial<EditingRule>) {
    if (!editing) return;
    setEditing({
      ...editing,
      rules: editing.rules.map((r, i) => (i === index ? { ...r, ...updates } : r)),
    });
  }

  const isSaving = createMutation.isPending || updateMutation.isPending;

  return (
    <div className="mx-auto max-w-6xl space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Experience Multipliers</h1>
          <p className="text-sm text-gray-500">
            Define rate and effort adjustments by chapter, location, and experience level.
          </p>
        </div>
        {!editing && (
          <button
            onClick={() => setEditing({ ...emptySet })}
            className="rounded-2xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700"
          >
            New multiplier set
          </button>
        )}
      </div>

      {/* Editor */}
      {editing && (
        <div className="rounded-3xl border border-gray-200 bg-white p-6 shadow-sm">
          <h2 className="mb-4 text-lg font-semibold text-gray-900">
            {editing.id ? "Edit multiplier set" : "New multiplier set"}
          </h2>

          <div className="mb-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1 flex items-center text-xs font-medium text-gray-500 uppercase">Name <InfoTooltip content="A descriptive name for this multiplier set. Used to identify it when applying multipliers to estimates." /></label>
              <input
                value={editing.name}
                onChange={(e) => setEditing({ ...editing, name: e.target.value })}
                className="w-full rounded-xl border border-gray-300 px-3 py-2 text-sm"
                placeholder="e.g. CGI Standard Multipliers"
              />
            </div>
            <div>
              <label className="mb-1 flex items-center text-xs font-medium text-gray-500 uppercase">Description <InfoTooltip content="Optional explanation of when this multiplier set should be used." /></label>
              <input
                value={editing.description}
                onChange={(e) => setEditing({ ...editing, description: e.target.value })}
                className="w-full rounded-xl border border-gray-300 px-3 py-2 text-sm"
                placeholder="Optional description"
              />
            </div>
          </div>

          <label className="mb-4 flex items-center gap-2 text-sm text-gray-600">
            <input
              type="checkbox"
              checked={editing.isDefault}
              onChange={(e) => setEditing({ ...editing, isDefault: e.target.checked })}
              className="rounded border-gray-300"
            />
            Default set (auto-selected when applying multipliers) <InfoTooltip content="When checked, this set is automatically selected when applying experience multipliers. Only one set can be default." />
          </label>

          {/* Rules table */}
          <div className="mb-4">
            <div className="mb-2 flex items-center justify-between">
              <h3 className="text-sm font-semibold text-gray-700">Rules ({editing.rules.length})</h3>
              <button
                onClick={addRule}
                className="rounded-xl border border-gray-300 px-3 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50"
              >
                + Add rule
              </button>
            </div>

            {editing.rules.length === 0 ? (
              <p className="rounded-xl bg-gray-50 p-4 text-center text-sm text-gray-400">
                No rules yet. Add rules to define rate and effort adjustments.
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                  <thead>
                    <tr className="border-b border-gray-200 text-xs uppercase tracking-wider text-gray-500">
                      <th className="py-2 pr-2 font-medium"><span className="flex items-center">Chapter <InfoTooltip content="The discipline/chapter this multiplier applies to. Leave blank to match all chapters." /></span></th>
                      <th className="px-2 py-2 font-medium"><span className="flex items-center">Location <InfoTooltip content="The country/location this multiplier targets. Used for nearshoring/offshoring cost adjustments." /></span></th>
                      <th className="px-2 py-2 font-medium"><span className="flex items-center">Level <InfoTooltip content="The seniority level (Junior, Mid, Senior, etc.). Juniors typically need a higher effort multiplier." /></span></th>
                      <th className="px-2 py-2 text-right font-medium"><span className="flex items-center justify-end">Cost mult. <InfoTooltip content="Multiplier applied to cost rates. E.g. 0.5 means 50% of the base cost rate (cheaper location)." /></span></th>
                      <th className="px-2 py-2 text-right font-medium"><span className="flex items-center justify-end">Bill mult. <InfoTooltip content="Multiplier applied to billing rates. E.g. 0.8 means the client is billed at 80% of the standard rate." /></span></th>
                      <th className="px-2 py-2 text-right font-medium"><span className="flex items-center justify-end">Shoring % <InfoTooltip content="Ratio of work done at the remote location (0-1). E.g. 0.7 means 70% remote, 30% local." /></span></th>
                      <th className="px-2 py-2 text-right font-medium"><span className="flex items-center justify-end">Add. effort % <InfoTooltip content="Additional effort overhead for coordination, e.g. 0.15 adds 15% extra hours for communication overhead." /></span></th>
                      <th className="pl-2 py-2 font-medium w-10"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {editing.rules.map((rule, i) => (
                      <tr key={i} className="border-b border-gray-100">
                        <td className="py-2 pr-2">
                          <input
                            value={rule.chapter}
                            onChange={(e) => updateRule(i, { chapter: e.target.value })}
                            list="chapter-presets"
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                            placeholder="Any"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            value={rule.location}
                            onChange={(e) => updateRule(i, { location: e.target.value })}
                            list="location-presets"
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                            placeholder="Any"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            value={rule.level}
                            onChange={(e) => updateRule(i, { level: e.target.value })}
                            list="level-presets"
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                            placeholder="Any"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            type="number"
                            step="0.01"
                            min="0"
                            value={rule.costMultiplier}
                            onChange={(e) => updateRule(i, { costMultiplier: parseFloat(e.target.value) || 0 })}
                            className="w-20 rounded-lg border border-gray-200 px-2 py-1 text-right text-sm tabular-nums"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            type="number"
                            step="0.01"
                            min="0"
                            value={rule.billMultiplier}
                            onChange={(e) => updateRule(i, { billMultiplier: parseFloat(e.target.value) || 0 })}
                            className="w-20 rounded-lg border border-gray-200 px-2 py-1 text-right text-sm tabular-nums"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            type="number"
                            step="0.01"
                            min="0"
                            max="1"
                            value={rule.shoringRatio}
                            onChange={(e) => updateRule(i, { shoringRatio: e.target.value })}
                            className="w-20 rounded-lg border border-gray-200 px-2 py-1 text-right text-sm tabular-nums"
                            placeholder="-"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            type="number"
                            step="0.01"
                            min="0"
                            value={rule.additionalEffortRatio}
                            onChange={(e) => updateRule(i, { additionalEffortRatio: e.target.value })}
                            className="w-20 rounded-lg border border-gray-200 px-2 py-1 text-right text-sm tabular-nums"
                            placeholder="-"
                          />
                        </td>
                        <td className="pl-2 py-2">
                          <button
                            onClick={() => removeRule(i)}
                            className="text-red-400 hover:text-red-600"
                            title="Remove"
                          >
                            x
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          <datalist id="chapter-presets">
            {CHAPTER_PRESETS.map((d) => (
              <option key={d} value={d} />
            ))}
          </datalist>
          <datalist id="location-presets">
            {LOCATION_PRESETS.map((d) => (
              <option key={d} value={d} />
            ))}
          </datalist>
          <datalist id="level-presets">
            {LEVEL_PRESETS.map((d) => (
              <option key={d} value={d} />
            ))}
          </datalist>

          <div className="flex gap-3">
            <button
              onClick={handleSave}
              disabled={isSaving || !editing.name.trim()}
              className="rounded-2xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
            >
              {isSaving ? "Saving..." : "Save"}
            </button>
            <button
              onClick={() => setEditing(null)}
              className="rounded-2xl border border-gray-300 px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50"
            >
              Cancel
            </button>
          </div>

          {(createMutation.error || updateMutation.error) && (
            <p className="mt-2 text-sm text-red-600">
              {createMutation.error?.message || updateMutation.error?.message}
            </p>
          )}
        </div>
      )}

      {/* List */}
      {isLoading && <p className="text-center text-sm text-gray-400">Loading...</p>}

      {sets && sets.length === 0 && !editing && (
        <div className="rounded-3xl border border-gray-200 bg-gray-50 p-8 text-center text-sm text-gray-500">
          No experience multiplier sets yet. Create one to define rate and effort adjustments.
        </div>
      )}

      {sets?.map((s) => (
        <div key={s.id} className="rounded-3xl border border-gray-200 bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <h3 className="text-base font-semibold text-gray-900">{s.name}</h3>
              {s.isDefault && (
                <span className="rounded-full bg-brand-100 px-2 py-0.5 text-xs font-medium text-brand-700">Default</span>
              )}
              <span className="text-sm text-gray-500">{s.rules.length} rules</span>
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setExpandedId(expandedId === s.id ? null : s.id)}
                className="rounded-xl border border-gray-300 px-3 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50"
              >
                {expandedId === s.id ? "Collapse" : "Expand"}
              </button>
              <button
                onClick={() => handleEdit(s)}
                className="rounded-xl border border-gray-300 px-3 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50"
              >
                Edit
              </button>
              <button
                onClick={() => setConfirmDelete(s.id)}
                className="rounded-xl border border-red-200 px-3 py-1 text-xs font-medium text-red-600 hover:bg-red-50"
              >
                Delete
              </button>
            </div>
          </div>
          {s.description && <p className="mt-1 text-sm text-gray-500">{s.description}</p>}

          {expandedId === s.id && s.rules.length > 0 && (
            <div className="mt-3 overflow-x-auto">
              <table className="w-full text-left text-sm">
                <thead>
                  <tr className="border-b border-gray-200 text-xs uppercase tracking-wider text-gray-500">
                    <th className="py-2 pr-3 font-medium"><span className="flex items-center">Chapter <InfoTooltip content="Discipline this multiplier applies to." /></span></th>
                    <th className="px-3 py-2 font-medium"><span className="flex items-center">Location <InfoTooltip content="Target country/region." /></span></th>
                    <th className="px-3 py-2 font-medium"><span className="flex items-center">Level <InfoTooltip content="Seniority level filter." /></span></th>
                    <th className="px-3 py-2 text-right font-medium"><span className="flex items-center justify-end">Cost mult. <InfoTooltip content="Factor applied to cost rates." /></span></th>
                    <th className="px-3 py-2 text-right font-medium"><span className="flex items-center justify-end">Bill mult. <InfoTooltip content="Factor applied to billing rates." /></span></th>
                    <th className="px-3 py-2 text-right font-medium"><span className="flex items-center justify-end">Shoring <InfoTooltip content="Share of work done remotely (0-100%)." /></span></th>
                    <th className="pl-3 py-2 text-right font-medium"><span className="flex items-center justify-end">Add. effort <InfoTooltip content="Extra effort overhead percentage." /></span></th>
                  </tr>
                </thead>
                <tbody>
                  {s.rules.map((r) => (
                    <tr key={r.id} className="border-b border-gray-100">
                      <td className="py-1.5 pr-3 text-gray-900">{r.chapter || "\u2014"}</td>
                      <td className="px-3 py-1.5 text-gray-700">{r.location || "\u2014"}</td>
                      <td className="px-3 py-1.5 text-gray-500">{r.level || "\u2014"}</td>
                      <td className="px-3 py-1.5 text-right tabular-nums text-gray-700">{r.costMultiplier.toFixed(2)}x</td>
                      <td className="px-3 py-1.5 text-right tabular-nums text-gray-700">{r.billMultiplier.toFixed(2)}x</td>
                      <td className="px-3 py-1.5 text-right tabular-nums text-gray-500">
                        {r.shoringRatio != null ? `${(r.shoringRatio * 100).toFixed(0)}%` : "\u2014"}
                      </td>
                      <td className="pl-3 py-1.5 text-right tabular-nums text-gray-500">
                        {r.additionalEffortRatio != null ? `${(r.additionalEffortRatio * 100).toFixed(0)}%` : "\u2014"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      ))}

      {confirmDelete && (
        <ConfirmDialog
          title="Delete multiplier set"
          message="Are you sure you want to delete this multiplier set? This action cannot be undone."
          confirmLabel="Delete"
          variant="danger"
          onConfirm={() => {
            deleteMutation.mutate({ id: confirmDelete });
            setConfirmDelete(null);
          }}
          onCancel={() => setConfirmDelete(null)}
        />
      )}
    </div>
  );
}
