import React, { useState } from "react";
import { PencilRuler, Trash2 } from "lucide-react";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  CardDescription,
} from "@/components/ui/card";

import { Feature } from "@/types";

const FeatureCard = ({
  feature,
  setFeatures,
  features,
}: {
  feature: Feature;
  setFeatures: React.Dispatch<React.SetStateAction<Feature[]>>;
  features: 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
      key={feature.uid}
      className="w-[350px] h-[200px] flex flex-col justify-between m-auto"
    >
      {isEditing ? (
        <CardHeader>
          <input
            type="text"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
            }}
            className="card-title-editable"
          />
          <textarea
            value={description}
            onChange={(e) => {
              setDescription(e.target.value);
            }}
            className="card-description-editable"
          />
        </CardHeader>
      ) : (
        <CardHeader>
          <CardTitle>{feature.name}</CardTitle>
          <CardDescription>{feature.description}</CardDescription>
        </CardHeader>
      )}

      <CardContent>
        <div className="flex text-muted-foreground justify-end space-x-4 cursor-pointer">
          {isEditing ? (
            <button
              className="hover:text-green-600"
              onClick={() => saveChanges()}
            >
              Save
            </button>
          ) : (
            <PencilRuler
              onClick={toggleEdit}
              className="hover:text-yellow-600"
              size={20}
              strokeWidth={1}
            />
          )}
          <Trash2
            onClick={() => {
              setFeatures(features.filter((f) => f.uid !== feature.uid));
            }}
            className="hover:text-red-500"
            size={20}
            strokeWidth={1}
          />
        </div>
      </CardContent>
    </Card>
  );
};

export default FeatureCard;
