"use client";

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

type CountryRow = {
  id: string;
  code: string;
  name: string;
  dailyWorkingHours: number;
  scheduleRules: unknown;
  isActive: boolean;
  metroCities: { id: string; name: string }[];
};

type EditingCountry = {
  id?: string;
  code: string;
  name: string;
  dailyWorkingHours: number;
  hasSpainRules: boolean;
  fridayHours: number;
  summerFrom: string;
  summerTo: string;
  summerHours: number;
  regularHours: number;
};

const emptyCountry: EditingCountry = {
  code: "",
  name: "",
  dailyWorkingHours: 8,
  hasSpainRules: false,
  fridayHours: 6.5,
  summerFrom: "07-01",
  summerTo: "09-15",
  summerHours: 6.5,
  regularHours: 9,
};

function parseSpainRules(rules: unknown): Partial<EditingCountry> {
  if (!rules || typeof rules !== "object") return { hasSpainRules: false };
  const r = rules as Record<string, unknown>;
  if (r.type !== "spain") return { hasSpainRules: false };
  const sp = r as { fridayHours?: number; summerPeriod?: { from?: string; to?: string }; summerHours?: number; regularHours?: number };
  return {
    hasSpainRules: true,
    fridayHours: sp.fridayHours ?? 6.5,
    summerFrom: sp.summerPeriod?.from ?? "07-01",
    summerTo: sp.summerPeriod?.to ?? "09-15",
    summerHours: sp.summerHours ?? 6.5,
    regularHours: sp.regularHours ?? 9,
  };
}

export function CountriesClient() {
  const [editing, setEditing] = useState<EditingCountry | null>(null);
  const [cityName, setCityName] = useState("");
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [confirmDeleteCity, setConfirmDeleteCity] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const utils = trpc.useUtils();
  const { data: countries, isLoading } = trpc.country.list.useQuery();

  // @ts-ignore TS2589: tRPC infers union type too deeply for nullable JSONB scheduleRules schema
  const createMut = trpc.country.create.useMutation({
    onSuccess: () => { void utils.country.list.invalidate(); setEditing(null); },
    onError: (e) => setError(e.message),
  });
  const updateMut = trpc.country.update.useMutation({
    onSuccess: () => { void utils.country.list.invalidate(); setEditing(null); },
    onError: (e) => setError(e.message),
  });
  const createCityMut = trpc.country.createCity.useMutation({
    onSuccess: () => { void utils.country.list.invalidate(); setCityName(""); },
    onError: (e) => setError(e.message),
  });
  const deleteCityMut = trpc.country.deleteCity.useMutation({
    onSuccess: () => void utils.country.list.invalidate(),
    onError: (e) => setError(e.message),
  });

  function openCreate() {
    setEditing({ ...emptyCountry });
    setError(null);
  }

  function openEdit(c: CountryRow) {
    const spainParts = parseSpainRules(c.scheduleRules);
    setEditing({
      id: c.id,
      code: c.code,
      name: c.name,
      dailyWorkingHours: c.dailyWorkingHours,
      hasSpainRules: false,
      fridayHours: 6.5,
      summerFrom: "07-01",
      summerTo: "09-15",
      summerHours: 6.5,
      regularHours: 9,
      ...spainParts,
    });
    setError(null);
  }

  function handleSave() {
    if (!editing) return;
    setError(null);

    const scheduleRules = editing.hasSpainRules
      ? {
          type: "spain" as const,
          fridayHours: editing.fridayHours,
          summerPeriod: { from: editing.summerFrom, to: editing.summerTo },
          summerHours: editing.summerHours,
          regularHours: editing.regularHours,
        }
      : null;

    if (editing.id) {
      updateMut.mutate({
        id: editing.id,
        data: {
          code: editing.code,
          name: editing.name,
          dailyWorkingHours: editing.dailyWorkingHours,
          scheduleRules,
        },
      });
    } else {
      createMut.mutate({
        code: editing.code,
        name: editing.name,
        dailyWorkingHours: editing.dailyWorkingHours,
        scheduleRules,
      });
    }
  }

  function handleAddCity(countryId: string) {
    if (!cityName.trim()) return;
    createCityMut.mutate({ countryId, name: cityName.trim() });
  }

  const isPending = createMut.isPending || updateMut.isPending;
  const rows = (countries ?? []) as unknown as CountryRow[];

  return (
    <div className="p-6 max-w-5xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-50">Countries</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Manage countries, daily working hours, and metro cities
          </p>
        </div>
        <button
          type="button"
          onClick={openCreate}
          className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium"
        >
          + Add Country
        </button>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 px-4 py-3 text-sm text-red-700 dark:text-red-400 flex items-center justify-between">
          {error}
          <button type="button" onClick={() => setError(null)} className="text-red-400 hover:text-red-600 text-lg leading-none">&times;</button>
        </div>
      )}

      {/* Country List */}
      <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
              <th className="text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center">Code <InfoTooltip content="ISO country code (e.g. DE, ES, IN). Used to identify the country in exports and API calls." /></span></th>
              <th className="text-left px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center">Name <InfoTooltip content="The full country name. Shown in dropdowns and resource location fields." /></span></th>
              <th className="text-center px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center justify-center">Daily Hours <InfoTooltip content="Standard working hours per day for this country. Used in capacity calculations to convert between days and hours." /></span></th>
              <th className="text-center px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center justify-center">Schedule <InfoTooltip content="Special schedule rules (e.g. Spain has reduced Friday hours and summer hours). 'Standard' uses the fixed daily hours value." /></span></th>
              <th className="text-center px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider"><span className="flex items-center justify-center">Cities <InfoTooltip content="Metro cities within this country. Used for location-specific rate cards and resource assignment." /></span></th>
              <th className="text-right px-4 py-3 font-medium text-gray-600 dark:text-gray-400 text-xs uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr><td colSpan={6} className="text-center py-8 text-gray-400">Loading...</td></tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr><td colSpan={6} className="text-center py-8 text-gray-400">No countries yet.</td></tr>
            )}
            {rows.map((c) => (
              <tr key={c.id} className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/30">
                <td className="px-4 py-3 font-mono font-medium text-gray-900 dark:text-gray-100">{c.code}</td>
                <td className="px-4 py-3 text-gray-900 dark:text-gray-100">{c.name}</td>
                <td className="px-4 py-3 text-center text-gray-600 dark:text-gray-400">{c.dailyWorkingHours}h</td>
                <td className="px-4 py-3 text-center">
                  {c.scheduleRules && typeof c.scheduleRules === "object" && (c.scheduleRules as Record<string, unknown>).type === "spain" ? (
                    <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400">Spain</span>
                  ) : (
                    <span className="text-gray-400 text-xs">Standard</span>
                  )}
                </td>
                <td className="px-4 py-3 text-center">
                  <button
                    type="button"
                    onClick={() => setExpandedId(expandedId === c.id ? null : c.id)}
                    className="text-xs text-brand-600 hover:text-brand-800 font-medium"
                  >
                    {c.metroCities.length} cities {expandedId === c.id ? "▲" : "▼"}
                  </button>
                </td>
                <td className="px-4 py-3 text-right">
                  <button type="button" onClick={() => openEdit(c)} className="text-xs text-brand-600 hover:text-brand-800 font-medium">Edit</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Expanded Metro Cities */}
      {expandedId && (() => {
        const country = rows.find((c) => c.id === expandedId);
        if (!country) return null;
        return (
          <div className="mt-4 bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              Metro Cities for {country.name}
            </h3>
            <div className="flex flex-wrap gap-2 mb-3">
              {country.metroCities.map((city) => (
                <span key={city.id} className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300">
                  {city.name}
                  <button
                    type="button"
                    onClick={() => setConfirmDeleteCity(city.id)}
                    className="text-gray-400 hover:text-red-500 text-xs leading-none ml-1"
                  >
                    &times;
                  </button>
                </span>
              ))}
              {country.metroCities.length === 0 && (
                <span className="text-sm text-gray-400">No metro cities yet</span>
              )}
            </div>
            <div className="flex gap-2">
              <input
                type="text"
                value={cityName}
                onChange={(e) => setCityName(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") handleAddCity(country.id); }}
                placeholder="New city name..."
                className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400 flex-1"
              />
              <button
                type="button"
                onClick={() => handleAddCity(country.id)}
                disabled={createCityMut.isPending || !cityName.trim()}
                className="px-3 py-1.5 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
              >
                Add
              </button>
            </div>
          </div>
        );
      })()}

      {/* Create/Edit Modal */}
      <AnimatedModal open={editing !== null} onClose={() => setEditing(null)} maxWidth="max-w-lg" className="flex flex-col max-h-[90vh]">
        {editing && (<>
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                {editing.id ? "Edit Country" : "Add Country"}
              </h2>
              <button type="button" onClick={() => setEditing(null)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-2xl leading-none">&times;</button>
            </div>

            <div className="overflow-y-auto flex-1 px-6 py-5 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Code <InfoTooltip content="2-3 letter ISO country code. Auto-uppercased." /></label>
                  <input
                    type="text"
                    value={editing.code}
                    onChange={(e) => setEditing({ ...editing, code: e.target.value.toUpperCase() })}
                    maxLength={3}
                    placeholder="DE"
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400 font-mono"
                  />
                </div>
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Daily Hours <InfoTooltip content="Standard working hours per day. Used to convert between hours and days in capacity calculations." /></label>
                  <input
                    type="number"
                    value={editing.dailyWorkingHours}
                    onChange={(e) => setEditing({ ...editing, dailyWorkingHours: parseFloat(e.target.value) || 8 })}
                    min={1}
                    max={24}
                    step={0.5}
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                  />
                </div>
              </div>

              <div>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Name <InfoTooltip content="Full country name shown in the UI." /></label>
                <input
                  type="text"
                  value={editing.name}
                  onChange={(e) => setEditing({ ...editing, name: e.target.value })}
                  placeholder="Germany"
                  className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                />
              </div>

              {/* Spain Schedule Rules */}
              <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={editing.hasSpainRules}
                    onChange={(e) => setEditing({ ...editing, hasSpainRules: e.target.checked })}
                    className="rounded border-gray-300 text-brand-600 focus:ring-brand-500"
                  />
                  Variable schedule (Spain-type) <InfoTooltip content="Enable for countries with variable working hours (e.g. reduced Friday/summer hours). Overrides the fixed daily hours with day-specific rules." />
                </label>

                {editing.hasSpainRules && (
                  <div className="mt-3 space-y-3 pl-6 border-l-2 border-amber-300 dark:border-amber-700">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Friday Hours <InfoTooltip content="Working hours on Fridays. Typically shorter than regular days." /></label>
                        <input
                          type="number"
                          value={editing.fridayHours}
                          onChange={(e) => setEditing({ ...editing, fridayHours: parseFloat(e.target.value) || 6.5 })}
                          step={0.5}
                          className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                        />
                      </div>
                      <div>
                        <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Regular Hours (Mon-Thu) <InfoTooltip content="Working hours Monday through Thursday outside the summer period." /></label>
                        <input
                          type="number"
                          value={editing.regularHours}
                          onChange={(e) => setEditing({ ...editing, regularHours: parseFloat(e.target.value) || 9 })}
                          step={0.5}
                          className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-3 gap-3">
                      <div>
                        <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Summer From <InfoTooltip content="Start of the summer period (MM-DD format). During summer, reduced hours apply." /></label>
                        <input
                          type="text"
                          value={editing.summerFrom}
                          onChange={(e) => setEditing({ ...editing, summerFrom: e.target.value })}
                          placeholder="07-01"
                          className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                        />
                      </div>
                      <div>
                        <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Summer To <InfoTooltip content="End of the summer period (MM-DD format)." /></label>
                        <input
                          type="text"
                          value={editing.summerTo}
                          onChange={(e) => setEditing({ ...editing, summerTo: e.target.value })}
                          placeholder="09-15"
                          className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                        />
                      </div>
                      <div>
                        <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Summer Hours <InfoTooltip content="Reduced daily working hours during the summer period." /></label>
                        <input
                          type="number"
                          value={editing.summerHours}
                          onChange={(e) => setEditing({ ...editing, summerHours: parseFloat(e.target.value) || 6.5 })}
                          step={0.5}
                          className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                        />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            <div className="flex items-center justify-end px-6 py-4 border-t border-gray-200 dark:border-gray-700 gap-3">
              <button type="button" onClick={() => setEditing(null)} className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200">Cancel</button>
              <button
                type="button"
                onClick={handleSave}
                disabled={isPending || !editing.code || !editing.name}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
              >
                {isPending ? "Saving..." : editing.id ? "Update" : "Create"}
              </button>
            </div>
        </>)}
      </AnimatedModal>

      {confirmDeleteCity && (
        <ConfirmDialog
          title="Delete metro city"
          message="Are you sure you want to delete this metro city?"
          confirmLabel="Delete"
          variant="danger"
          onConfirm={() => {
            deleteCityMut.mutate({ id: confirmDeleteCity });
            setConfirmDeleteCity(null);
          }}
          onCancel={() => setConfirmDeleteCity(null)}
        />
      )}
    </div>
  );
}
