import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import type { AuthorWithStats } from "./types";

interface AuthorEditorProps {
  author?: Partial<AuthorWithStats>;
  onSave: (author: AuthorWithStats) => void;
  isSaving?: boolean;
  error?: string;
}

export function AuthorEditor({
  author = {},
  onSave,
  isSaving,
  error,
}: AuthorEditorProps) {
  const [form, setForm] = useState<Partial<AuthorWithStats>>({ ...author });
  const [formError, setFormError] = useState<string | null>(null);

  function handleChange<K extends keyof AuthorWithStats>(
    key: K,
    value: AuthorWithStats[K]
  ) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  function validate(): boolean {
    if (!form.name || form.name.trim().length < 2) {
      setFormError("Name is required and must be at least 2 characters.");
      return false;
    }
    return true;
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setFormError(null);
    if (!validate()) return;
    onSave({
      ...author,
      ...form,
      name: form.name?.trim() || "",
      biography: form.biography?.trim() || "",
    } as AuthorWithStats);
  }

  return (
    <Card className="max-w-xl mx-auto">
      <CardContent>
        <form className="space-y-4" onSubmit={handleSubmit}>
          <div>
            <Label htmlFor="author-name" className="mb-1">
              Name
            </Label>
            <Input
              id="author-name"
              value={form.name || ""}
              onChange={(e) => handleChange("name", e.target.value)}
              required
              minLength={2}
              placeholder="Author name"
            />
          </div>
          <div>
            <Label htmlFor="author-bio" className="mb-1">
              Biography
            </Label>
            <Textarea
              id="author-bio"
              value={form.biography || ""}
              onChange={(e) => handleChange("biography", e.target.value)}
              rows={4}
              placeholder="Short biography"
            />
          </div>
          <div className="flex gap-4">
            <div className="flex-1">
              <Label htmlFor="author-birth" className="mb-1">
                Birth Year
              </Label>
              <Input
                id="author-birth"
                type="number"
                value={form.birthYear ?? ""}
                onChange={(e) =>
                  handleChange(
                    "birthYear",
                    e.target.value ? Number(e.target.value) : undefined
                  )
                }
                min={1000}
                max={new Date().getFullYear()}
                placeholder="e.g. 1821"
              />
            </div>
            <div className="flex-1">
              <Label htmlFor="author-death" className="mb-1">
                Death Year
              </Label>
              <Input
                id="author-death"
                type="number"
                value={form.deathYear ?? ""}
                onChange={(e) =>
                  handleChange(
                    "deathYear",
                    e.target.value ? Number(e.target.value) : undefined
                  )
                }
                min={1000}
                max={new Date().getFullYear()}
                placeholder="e.g. 1881"
              />
            </div>
          </div>
          <div>
            <Label htmlFor="author-country" className="mb-1">
              Country
            </Label>
            <Input
              id="author-country"
              value={form.country || ""}
              onChange={(e) => handleChange("country", e.target.value)}
              placeholder="Country of origin"
            />
          </div>
          <div>
            <Label htmlFor="author-portrait" className="mb-1">
              Portrait URL
            </Label>
            <Input
              id="author-portrait"
              value={form.portrait || ""}
              onChange={(e) => handleChange("portrait", e.target.value)}
              placeholder="Image URL"
            />
          </div>
          {(formError || error) && (
            <div className="text-red-500 text-sm">{formError || error}</div>
          )}
          <Button type="submit" disabled={isSaving}>
            {isSaving ? "Saving..." : "Save Author"}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
