import { useState } from 'react';
import { Swords, X } from 'lucide-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 { cn } from '@/lib/cn';
import { useEncounters, useEncounter } from './hooks';
import { EncounterTracker } from './EncounterTracker';
import { RollFeed } from '@/features/player/RollFeed';

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
        eyebrow="Roll for initiative"
        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.5">
            <div className="smallcaps px-1 pb-1">Encounters</div>
            {encounters.map((e) => (
              <div
                key={e.id}
                className={cn(
                  'group flex items-center gap-1 rounded-xl border px-2 transition-colors',
                  validSelection?.id === e.id
                    ? 'border-accent bg-accent-glow'
                    : 'border-line bg-panel hover:border-line-strong',
                )}
              >
                <button
                  className="flex flex-1 items-center gap-2.5 py-2 text-left text-sm"
                  onClick={() => setActiveEncounter(e.id)}
                >
                  <Swords
                    size={16}
                    aria-hidden
                    className={validSelection?.id === e.id ? 'text-accent-deep' : 'text-faint'}
                  />
                  <span className="min-w-0">
                    <span className="block truncate font-display font-medium text-ink">{e.name}</span>
                    <span className="text-xs text-muted">
                      {STATUS_LABEL[e.status]} · {e.combatants.length} combatants
                    </span>
                  </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);
                  }}
                >
                  <X size={15} aria-hidden />
                </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>
      )}

      {/* Players' live rolls reach the GM here while hosting a session. */}
      <RollFeed />

      <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>
  );
}
