"use client";

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

type EffortUnitMode = "per_frame" | "per_item" | "flat";

type EditingRule = {
  id?: string;
  scopeType: string;
  discipline: string;
  chapter: string;
  unitMode: EffortUnitMode;
  hoursPerUnit: number;
  description: string;
  sortOrder: number;
};

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

const UNIT_MODE_LABELS: Record<EffortUnitMode, string> = {
  per_frame: "Per frame",
  per_item: "Per item",
  flat: "Flat",
};

const SCOPE_TYPE_PRESETS = ["SHOT", "ASSET", "ENVIRONMENT", "SEQUENCE", "OTHER"];
const DISCIPLINE_PRESETS = [
  "3D Animation",
  "3D Lighting",
  "3D Modeling",
  "3D Rigging",
  "3D Environment",
  "Compositing",
  "Motion Graphics",
  "Art Direction",
  "Conception / R&D",
  "Project Management",
  "Production Supervisor",
  "DataPrep",
  "Audio Production",
];

const emptyRule: EditingRule = {
  scopeType: "SHOT",
  discipline: "",
  chapter: "",
  unitMode: "per_frame",
  hoursPerUnit: 0,
  description: "",
  sortOrder: 0,
};

const emptyRuleSet: EditingRuleSet = {
  name: "",
  description: "",
  isDefault: false,
  rules: [],
};

export function EffortRulesClient() {
  const utils = trpc.useUtils();
  const { data: ruleSets, isLoading } = trpc.effortRule.list.useQuery();

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

  const [editing, setEditing] = useState<EditingRuleSet | null>(null);
  const [expandedId, setExpandedId] = 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) => ({
        scopeType: r.scopeType,
        discipline: r.discipline,
        ...(r.chapter ? { chapter: r.chapter } : {}),
        unitMode: r.unitMode,
        hoursPerUnit: r.hoursPerUnit,
        ...(r.description ? { description: r.description } : {}),
        sortOrder: i,
      })),
    };

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

  function handleEdit(ruleSet: NonNullable<typeof ruleSets>[number]) {
    setEditing({
      id: ruleSet.id,
      name: ruleSet.name,
      description: ruleSet.description ?? "",
      isDefault: ruleSet.isDefault,
      rules: ruleSet.rules.map((r) => ({
        id: r.id,
        scopeType: r.scopeType,
        discipline: r.discipline,
        chapter: r.chapter ?? "",
        unitMode: r.unitMode as EffortUnitMode,
        hoursPerUnit: r.hoursPerUnit,
        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-5xl space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Effort Rules</h1>
          <p className="text-sm text-gray-500">
            Define rules for auto-generating demand lines from scope items.
          </p>
        </div>
        {!editing && (
          <button
            onClick={() => setEditing({ ...emptyRuleSet })}
            className="rounded-2xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700"
          >
            New rule 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 rule set" : "New rule 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 rule set, e.g. 'CGI Standard Rules'. Used to identify the set when linking it 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 Rules"
              />
            </div>
            <div>
              <label className="mb-1 flex items-center text-xs font-medium text-gray-500 uppercase">Description <InfoTooltip content="Optional notes about when this rule 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 rule set (auto-selected for new estimates) <InfoTooltip content="When checked, this set is pre-selected when creating new estimates. 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 how scope items expand into demand lines.
              </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">Scope type <InfoTooltip content="The type of deliverable this rule applies to: Shot, Asset, Environment, Sequence, or Other." /></span></th>
                      <th className="px-2 py-2 font-medium"><span className="flex items-center">Discipline <InfoTooltip content="The production discipline (e.g. 3D Animation, Compositing) that this rule generates demand for." /></span></th>
                      <th className="px-2 py-2 font-medium"><span className="flex items-center">Chapter <InfoTooltip content="Optional grouping within a discipline. Used to organize demand lines in the estimate staffing tab." /></span></th>
                      <th className="px-2 py-2 font-medium"><span className="flex items-center">Unit mode <InfoTooltip content="How hours are calculated: 'Per frame' multiplies by frame count, 'Per item' by item count, 'Flat' is a fixed amount." /></span></th>
                      <th className="px-2 py-2 text-right font-medium"><span className="flex items-center justify-end">Hours/unit <InfoTooltip content="The number of hours per unit. Combined with the unit mode and scope item count, this pre-fills the total effort in estimates." /></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">
                          <select
                            value={rule.scopeType}
                            onChange={(e) => updateRule(i, { scopeType: e.target.value })}
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                          >
                            {SCOPE_TYPE_PRESETS.map((t) => (
                              <option key={t} value={t}>{t}</option>
                            ))}
                          </select>
                        </td>
                        <td className="px-2 py-2">
                          <input
                            value={rule.discipline}
                            onChange={(e) => updateRule(i, { discipline: e.target.value })}
                            list="discipline-presets"
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                            placeholder="Discipline"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <input
                            value={rule.chapter}
                            onChange={(e) => updateRule(i, { chapter: e.target.value })}
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                            placeholder="Chapter"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <select
                            value={rule.unitMode}
                            onChange={(e) => updateRule(i, { unitMode: e.target.value as EffortUnitMode })}
                            className="w-full rounded-lg border border-gray-200 px-2 py-1 text-sm"
                          >
                            {(Object.entries(UNIT_MODE_LABELS) as [EffortUnitMode, string][]).map(([value, label]) => (
                              <option key={value} value={value}>{label}</option>
                            ))}
                          </select>
                        </td>
                        <td className="px-2 py-2">
                          <input
                            type="number"
                            step="0.01"
                            min="0"
                            value={rule.hoursPerUnit}
                            onChange={(e) => updateRule(i, { hoursPerUnit: 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="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="discipline-presets">
            {DISCIPLINE_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>}

      {ruleSets && ruleSets.length === 0 && !editing && (
        <div className="rounded-3xl border border-gray-200 bg-gray-50 p-8 text-center text-sm text-gray-500">
          No effort rule sets yet. Create one to define how scope items expand into demand lines.
        </div>
      )}

      {ruleSets?.map((rs) => (
        <div key={rs.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">{rs.name}</h3>
              {rs.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">{rs.rules.length} rules</span>
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setExpandedId(expandedId === rs.id ? null : rs.id)}
                className="rounded-xl border border-gray-300 px-3 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50"
              >
                {expandedId === rs.id ? "Collapse" : "Expand"}
              </button>
              <button
                onClick={() => handleEdit(rs)}
                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={() => {
                  if (confirm(`Delete rule set "${rs.name}"?`)) {
                    deleteMutation.mutate({ id: rs.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>
          {rs.description && <p className="mt-1 text-sm text-gray-500">{rs.description}</p>}

          {expandedId === rs.id && rs.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">Scope type <InfoTooltip content="The deliverable type (Shot, Asset, etc.) this rule targets." /></span></th>
                    <th className="px-3 py-2 font-medium"><span className="flex items-center">Discipline <InfoTooltip content="The production discipline this demand line is for." /></span></th>
                    <th className="px-3 py-2 font-medium"><span className="flex items-center">Chapter <InfoTooltip content="Optional sub-grouping within the discipline." /></span></th>
                    <th className="px-3 py-2 font-medium"><span className="flex items-center">Unit mode <InfoTooltip content="Per frame, per item, or flat hours calculation mode." /></span></th>
                    <th className="pl-3 py-2 text-right font-medium"><span className="flex items-center justify-end">Hours/unit <InfoTooltip content="Hours multiplied by the scope item count to compute total effort." /></span></th>
                  </tr>
                </thead>
                <tbody>
                  {rs.rules.map((r) => (
                    <tr key={r.id} className="border-b border-gray-100">
                      <td className="py-1.5 pr-3 text-gray-900">{r.scopeType}</td>
                      <td className="px-3 py-1.5 text-gray-700">{r.discipline}</td>
                      <td className="px-3 py-1.5 text-gray-500">{r.chapter || "\u2014"}</td>
                      <td className="px-3 py-1.5 text-gray-500">{UNIT_MODE_LABELS[r.unitMode as EffortUnitMode] ?? r.unitMode}</td>
                      <td className="pl-3 py-1.5 text-right tabular-nums text-gray-700">{r.hoursPerUnit}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
