import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { campaignsRepo } from '@/lib/db/repositories';
import { SYSTEM_OPTIONS } from '@/lib/rules';
import { useUiStore } from '@/stores/uiStore';
import { useCampaigns } from './hooks';
import type { Campaign } from '@/lib/schemas';
import { Page, PageHeader, EmptyState } from '@/components/ui/Page';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { Field, Input, Select, Textarea } from '@/components/ui/Input';

export function CampaignsPage() {
  const campaigns = useCampaigns();
  const [creating, setCreating] = useState(false);
  const [editing, setEditing] = useState<Campaign | null>(null);

  return (
    <Page>
      <PageHeader
        title="Campaigns"
        subtitle="Each campaign holds its own characters, encounters, and dice history."
        actions={
          <Button variant="primary" onClick={() => setCreating(true)}>
            + New campaign
          </Button>
        }
      />

      {campaigns.length === 0 ? (
        <EmptyState
          title="No campaigns yet"
          hint="Create your first campaign to start tracking characters and combat."
          action={
            <Button variant="primary" onClick={() => setCreating(true)}>
              + New campaign
            </Button>
          }
        />
      ) : (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {campaigns.map((c) => (
            <CampaignCard key={c.id} campaign={c} onEdit={() => setEditing(c)} />
          ))}
        </div>
      )}

      {creating && <CampaignFormModal onClose={() => setCreating(false)} />}
      {editing && <CampaignFormModal campaign={editing} onClose={() => setEditing(null)} />}
    </Page>
  );
}

function CampaignCard({ campaign, onEdit }: { campaign: Campaign; onEdit: () => void }) {
  const navigate = useNavigate();
  const setActive = useUiStore((s) => s.setActiveCampaign);
  const activeId = useUiStore((s) => s.activeCampaignId);
  const [confirming, setConfirming] = useState(false);

  const open = () => {
    setActive(campaign.id);
    void navigate({ to: '/characters' });
  };

  return (
    <div className="group relative flex flex-col rounded-lg border border-line bg-panel p-4">
      {activeId === campaign.id && (
        <span className="absolute right-3 top-3 rounded-full bg-accent/15 px-2 py-0.5 text-xs text-accent">
          Active
        </span>
      )}
      <div className="text-xs font-medium uppercase tracking-wide text-muted">
        {campaign.system === '5e' ? 'D&D 5e' : 'Pathfinder 2e'}
      </div>
      <h3 className="mt-1 font-display text-lg font-semibold text-ink">{campaign.name}</h3>
      {campaign.description && (
        <p className="mt-1 line-clamp-3 text-sm text-muted">{campaign.description}</p>
      )}
      <div className="mt-4 flex items-center gap-2">
        <Button size="sm" variant="primary" onClick={open}>
          Open
        </Button>
        <Button size="sm" variant="ghost" onClick={onEdit}>
          Edit
        </Button>
        <Button
          size="sm"
          variant="ghost"
          className="ml-auto text-danger hover:bg-danger/10"
          onClick={() => setConfirming(true)}
        >
          Delete
        </Button>
      </div>

      <Modal
        open={confirming}
        onClose={() => setConfirming(false)}
        title="Delete campaign?"
        footer={
          <>
            <Button variant="ghost" onClick={() => setConfirming(false)}>
              Cancel
            </Button>
            <Button
              variant="danger"
              onClick={async () => {
                await campaignsRepo.remove(campaign.id);
                if (activeId === campaign.id) setActive(null);
                setConfirming(false);
              }}
            >
              Delete everything
            </Button>
          </>
        }
      >
        <p className="text-sm text-muted">
          This permanently deletes <strong className="text-ink">{campaign.name}</strong> and all of its
          characters, encounters, and dice history. This cannot be undone.
        </p>
      </Modal>
    </div>
  );
}

function CampaignFormModal({ campaign, onClose }: { campaign?: Campaign; onClose: () => void }) {
  const setActive = useUiStore((s) => s.setActiveCampaign);
  const [name, setName] = useState(campaign?.name ?? '');
  const [system, setSystem] = useState(campaign?.system ?? '5e');
  const [description, setDescription] = useState(campaign?.description ?? '');
  const [error, setError] = useState<string | null>(null);

  const save = async () => {
    if (name.trim() === '') {
      setError('Name is required');
      return;
    }
    if (campaign) {
      await campaignsRepo.update(campaign.id, { name: name.trim(), system, description });
    } else {
      const created = await campaignsRepo.create({ name: name.trim(), system, description });
      setActive(created.id);
    }
    onClose();
  };

  return (
    <Modal
      open
      onClose={onClose}
      title={campaign ? 'Edit campaign' : 'New campaign'}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>
            Cancel
          </Button>
          <Button variant="primary" onClick={save}>
            {campaign ? 'Save' : 'Create'}
          </Button>
        </>
      }
    >
      <div className="space-y-4">
        <Field label="Name">
          <Input
            data-autofocus
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              setError(null);
            }}
            placeholder="Curse of Strahd"
          />
        </Field>
        <Field label="System">
          <Select
            value={system}
            disabled={!!campaign}
            onChange={(e) => setSystem(e.target.value as typeof system)}
          >
            {SYSTEM_OPTIONS.map((o) => (
              <option key={o.id} value={o.id}>
                {o.label}
              </option>
            ))}
          </Select>
        </Field>
        <Field label="Description">
          <Textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="A gothic horror campaign in the mists of Barovia…"
          />
        </Field>
        {error && <p className="text-sm text-danger">{error}</p>}
      </div>
    </Modal>
  );
}
