import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { createLedger, SplintError } from '../api/client';
import { addRecentLedger } from '../recent';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Item, ItemContent, ItemTitle, ItemActions } from '@/components/ui/item';
import { Label } from '@/components/ui/label';
import { Pencil, Trash2 } from 'lucide-react';
import type { Person } from '@splint/shared';
import { toast } from 'sonner';

export function CreateLedger() {
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [people, setPeople] = useState<Person[]>([]);
  const [newPersonName, setNewPersonName] = useState('');
  const [personError, setPersonError] = useState('');
  const [editingPersonId, setEditingPersonId] = useState<string | null>(null);
  const [editPersonName, setEditPersonName] = useState('');
  const [deletePersonId, setDeletePersonId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [validation, setValidation] = useState<Record<string, string>>({});

  // ── Person CRUD handlers (local, no API calls) ─────────────────────────

  function handleAddPerson() {
    const name = newPersonName.trim();
    if (!name) {
      setPersonError('Name cannot be empty.');
      return;
    }
    setPersonError('');
    setPeople((prev) => [
      ...prev,
      { id: crypto.randomUUID(), name },
    ]);
    setNewPersonName('');
  }

  function startEditPerson(id: string, current: string) {
    setEditingPersonId(id);
    setEditPersonName(current);
  }

  function handleSavePersonName() {
    if (!editingPersonId) return;
    const name = editPersonName.trim();
    if (!name) return;
    setPeople((prev) =>
      prev.map((p) =>
        p.id === editingPersonId ? { ...p, name } : p,
      ),
    );
    setEditingPersonId(null);
  }

  function cancelEditPerson() {
    setEditingPersonId(null);
  }

  function confirmRemove(personId: string) {
    setDeletePersonId(personId);
  }

  function handleRemovePerson() {
    if (!deletePersonId) return;
    setPeople((prev) => prev.filter((p) => p.id !== deletePersonId));
    setDeletePersonId(null);
  }

  // Post-creation confirmation state
  const [created, setCreated] = useState<{
    id: string;
    key: string;
    inviteUrl: string;
  } | null>(null);

  function validate(): boolean {
    const v: Record<string, string> = {};
    if (!name.trim()) v.name = 'Ledger name is required.';
    if (people.length === 0) v.people = 'Add at least one person.';
    setValidation(v);
    return Object.keys(v).length === 0;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    if (!validate()) return;
    setLoading(true);
    try {
      const { id, key } = await createLedger(name.trim(), {
        people,
        expenses: [],
        transfers: [],
      });

      localStorage.setItem(`splint-key:${id}`, key);
      addRecentLedger({ id, name: name.trim() });

      setCreated({
        id,
        key,
        inviteUrl: `${window.location.origin}/ledger/${id}`,
      });
    } catch (err) {
      const msg = err instanceof SplintError
        ? err.message
        : err instanceof Error ? err.message : 'Failed to create ledger.';
      setError(msg);
    } finally {
      setLoading(false);
    }
  }

  // ── Post-creation confirmation screen ─────────────────────────────────

  if (created) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <main className="container max-w-md mx-auto px-4">
          <Card>
            <CardHeader>
              <CardTitle>Ledger created!</CardTitle>
              <CardDescription>
                Share the encryption key and invite link with your group so they can access
                this ledger. The key is never stored on the server — if you
                lose it, the data cannot be recovered.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>Invite link to the ledger</Label>
                <div className="flex gap-2">
                  <Input
                    value={created.inviteUrl}
                    readOnly
                    className="text-xs"
                    onClick={(e) => (e.target as HTMLInputElement).select()}
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={async () => {
                      await navigator.clipboard.writeText(created.inviteUrl);
                      toast('Link copied!');
                    }}
                  >
                    Copy
                  </Button>
                </div>
              </div>

              <div className="space-y-2">
                <Label>Encryption key</Label>
                <div className="flex gap-2">
                  <Input
                    value={created.key}
                    readOnly
                    className="font-mono text-xs"
                    onClick={(e) => (e.target as HTMLInputElement).select()}
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={async () => {
                      await navigator.clipboard.writeText(created.key);
                      toast('Key copied!');
                    }}
                  >
                    Copy
                  </Button>
                </div>
              </div>

              <Button
                variant="default"
                className="w-full"
                onClick={() => navigate(`/ledger/${created.id}`)}
              >
                Continue to ledger
              </Button>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  // ── Creation form ─────────────────────────────────────────────────────

  return (
    <div className="container max-w-2xl mx-auto px-4 mt-8">
      <Button variant="ghost" asChild className="mb-4">
        <Link to="/">← Home</Link>
      </Button>

      <Card>
        <CardHeader>
          <CardTitle>Create a new ledger</CardTitle>
          <CardDescription>
            Track shared expenses with a group. You'll get an invite link to share.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">Ledger name</Label>
              <Input
                id="name"
                type="text"
                value={name}
                onChange={(e) => { setName(e.target.value); setValidation({}); }}
                placeholder="Trip to Paris"
                autoFocus
                className={validation.name ? 'border-destructive' : ''}
              />
              {validation.name && <p className="text-sm text-destructive">{validation.name}</p>}
            </div>

            <div className="space-y-2">
              <Label>People</Label>
              {people.length > 0 && (
                <div className="space-y-1">
                  {people.map((p) => {
                    if (editingPersonId === p.id) {
                      return (
                        <div key={p.id} className="flex gap-2 py-2">
                          <Input
                            type="text"
                            value={editPersonName}
                            onChange={(e) => setEditPersonName(e.target.value)}
                            autoFocus
                            className="flex-1"
                            aria-label="Edit person name"
                          />
                          <Button type="button" variant="default" size="sm" onClick={handleSavePersonName}>
                            Save
                          </Button>
                          <Button type="button" variant="outline" size="sm" onClick={cancelEditPerson}>
                            Cancel
                          </Button>
                        </div>
                      );
                    }
                    if (deletePersonId === p.id) {
                      return (
                        <div key={p.id} className="flex gap-2 items-center py-2">
                          <p className="text-xs text-muted-foreground flex-1">
                            Remove <strong>{p.name}</strong>?
                          </p>
                          <Button variant="destructive" size="sm" onClick={handleRemovePerson}>
                            Remove
                          </Button>
                          <Button variant="outline" size="sm" onClick={() => setDeletePersonId(null)}>
                            Keep
                          </Button>
                        </div>
                      );
                    }
                    return (
                      <Item key={p.id} variant="default" size="xs">
                        <ItemContent>
                          <ItemTitle>
                            <span className="font-medium">{p.name}</span>
                          </ItemTitle>
                        </ItemContent>
                        <ItemActions>
                          <Button
                            variant="ghost"
                            size="icon-sm"
                            onClick={() => startEditPerson(p.id, p.name)}
                            aria-label={`Rename ${p.name}`}
                          >
                            <Pencil />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon-sm"
                            onClick={() => confirmRemove(p.id)}
                            aria-label={`Remove ${p.name}`}
                          >
                            <Trash2 className="text-destructive" />
                          </Button>
                        </ItemActions>
                      </Item>
                    );
                  })}
                </div>
              )}
              {people.length === 0 && (
                <p className="text-xs text-muted-foreground py-2">No people yet.</p>
              )}
              <div className="flex gap-2">
                <Input
                  type="text"
                  value={newPersonName}
                  onChange={(e) => {
                    setNewPersonName(e.target.value);
                    setPersonError('');
                    setValidation({});
                  }}
                  placeholder="Add person..."
                  className="flex-1"
                  aria-label="New person name"
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      handleAddPerson();
                    }
                  }}
                />
                <Button type="button" size="sm" onClick={handleAddPerson}>
                  Add
                </Button>
              </div>
              {personError && (
                <p className="text-xs text-destructive" role="alert">{personError}</p>
              )}
              {validation.people && (
                <p className="text-sm text-destructive">{validation.people}</p>
              )}
            </div>

            {error && (
              <Card className="border-destructive">
                <CardContent className="p-4 text-sm text-destructive">
                  {error}
                </CardContent>
              </Card>
            )}

            <Button type="submit" variant="default" className="w-full" disabled={loading}>
              {loading ? 'Creating...' : 'Create Ledger'}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
