import { useState } from 'react';
import type { Campaign } from '@/lib/schemas';
import { encountersRepo } from '@/lib/db/repositories';
import { useUiStore } from '@/stores/uiStore';
import { Page, PageHeader, EmptyState, RequireCampaign } from '@/components/ui/Page';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { useEncounters, useEncounter } from './hooks';
import { EncounterTracker } from './EncounterTracker';

export function CombatPage() {
  return <RequireCampaign>{(campaign) => <Combat campaign={campaign} />}</RequireCampaign>;
}

const STATUS_LABEL = { planning: 'Not started', active: 'In progress', ended: 'Ended' } as const;

function Combat({ campaign }: { campaign: Campaign }) {
  const encounters = useEncounters(campaign.id);
  const activeEncounterId = useUiStore((s) => s.activeEncounterId);
  const setActiveEncounter = useUiStore((s) => s.setActiveEncounter);
  const selected = useEncounter(activeEncounterId);
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');

  // Only treat the selection as valid if it belongs to this campaign.
  const validSelection = selected && selected.campaignId === campaign.id ? selected : undefined;

  const create = async () => {
    const name = newName.trim() || 'Encounter';
    const enc = await encountersRepo.create(campaign.id, name);
    setActiveEncounter(enc.id);
    setNewName('');
    setCreating(false);
  };

  return (
    <Page>
      <PageHeader
        title="Combat"
        subtitle={campaign.name}
        actions={
          <Button variant="primary" onClick={() => setCreating(true)}>
            + New encounter
          </Button>
        }
      />

      {encounters.length === 0 ? (
        <EmptyState
          title="No encounters yet"
          hint="Create an encounter, add combatants, roll initiative, and run the fight."
          action={
            <Button variant="primary" onClick={() => setCreating(true)}>
              + New encounter
            </Button>
          }
        />
      ) : (
        <div className="grid gap-6 lg:grid-cols-[240px_1fr]">
          <aside className="space-y-1">
            {encounters.map((e) => (
              <div
                key={e.id}
                className={
                  'group flex items-center gap-1 rounded-md border px-2 ' +
                  (validSelection?.id === e.id ? 'border-accent bg-elevated' : 'border-line')
                }
              >
                <button
                  className="flex-1 py-2 text-left text-sm"
                  onClick={() => setActiveEncounter(e.id)}
                >
                  <span className="block truncate text-ink">{e.name}</span>
                  <span className="text-xs text-muted">
                    {STATUS_LABEL[e.status]} · {e.combatants.length} combatants
                  </span>
                </button>
                <button
                  className="px-1 text-muted opacity-0 transition-opacity hover:text-danger group-hover:opacity-100"
                  aria-label={`Delete ${e.name}`}
                  onClick={async () => {
                    await encountersRepo.remove(e.id);
                    if (activeEncounterId === e.id) setActiveEncounter(null);
                  }}
                >
                  ✕
                </button>
              </div>
            ))}
          </aside>

          <div>
            {validSelection ? (
              <EncounterTracker encounter={validSelection} campaign={campaign} />
            ) : (
              <EmptyState title="Select an encounter" hint="Pick one from the list, or create a new one." />
            )}
          </div>
        </div>
      )}

      <Modal
        open={creating}
        onClose={() => setCreating(false)}
        title="New encounter"
        footer={
          <>
            <Button variant="ghost" onClick={() => setCreating(false)}>
              Cancel
            </Button>
            <Button variant="primary" onClick={create}>
              Create
            </Button>
          </>
        }
      >
        <Input
          data-autofocus
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && create()}
          placeholder="Ambush on the road"
        />
      </Modal>
    </Page>
  );
}
