import { useState } from "react";

import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";

import { Pencil2Icon, TrashIcon } from "@radix-ui/react-icons";

type Feature = { uid: string; name: string; description: string };
export function FeatureCard({
  feature,
  features,
  setFeatures,
}: {
  feature: Feature;
  features: Feature[];
  setFeatures: React.Dispatch<React.SetStateAction<Feature[]>>;
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [name, setName] = useState(feature.name);
  const [description, setDescription] = useState(feature.description);

  const toggleEdit = () => {
    setIsEditing(!isEditing);
  };

  const saveChanges = () => {
    setFeatures(
      features.map((_feature) => {
        if (_feature.uid === feature.uid) {
          return { ..._feature, name: name, description: description };
        }
        return _feature;
      })
    );
    toggleEdit();
  };

  return (
    <Card className="shadow-none">
      {isEditing ? (
        <>
          <CardHeader>
            <CardTitle>
              <Input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </CardContent>
          <CardFooter className="flex flex-row space-x-2">
            <Button size="sm" variant="default" onClick={saveChanges}>
              Save
            </Button>
            <Button
              size="icon"
              variant="destructive"
              onClick={() =>
                setFeatures(features.filter((f) => f.uid !== feature.uid))
              }
            >
              <TrashIcon />
            </Button>
          </CardFooter>
        </>
      ) : (
        <>
          <CardHeader>
            <CardTitle>{feature.name}</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-xs">{feature.description}</p>
          </CardContent>
          <CardFooter className="flex flex-row space-x-2">
            <Button size="icon" variant="secondary">
              <Pencil2Icon onClick={toggleEdit} />
            </Button>
            <Button size="icon" variant="destructive">
              <TrashIcon
                onClick={() => {
                  setFeatures(features.filter((f) => f.uid !== feature.uid));
                }}
              />
            </Button>
          </CardFooter>
        </>
      )}
    </Card>
  );
}
