import { Button } from "../../../../../components/ui/button";
import { Checkbox } from "../../../../../components/ui/checkbox";
import { Label } from "../../../../../components/ui/label";
import { useAppForm } from "../../../../../lib/formStuff";
import { useCardStore } from "../../-lib/store/useCardStore";

export default function Cards(card: any) {
	const { addCard, removeCard, cards } = useCardStore();
	let existing: any = cards.filter((n: any) => n.name === card.name);

	//console.log(existing);
	const form = useAppForm({
		defaultValues: {
			name: existing[0]?.name || card.name,
			rowType: existing[0]?.type ?? card.rowType,
			age: existing[0]?.age ?? 90,
			active: existing[0]?.active ?? false,
		},
		onSubmit: async ({ value }) => {
			//console.log(value);
			const testCard: any = cards.filter((i: any) => i.name === value.name);

			if (value.active) {
				const newCard = {
					name: `${value.name}`,
					rowType: value.rowType,
					age: value.age ?? 90,
					active: value.active,
				};
				if (testCard.length > 0) {
					removeCard(value.name);
					addCard(newCard);
					return;
				}
				// change the name for a type card

				addCard(newCard);
			} else {
				removeCard(value.name);
			}
		},
	});
	return (
		<div className="border-solid border-2 m-2">
			<p>{card.name}</p>
			<form
				onSubmit={(e) => {
					e.preventDefault();
					e.stopPropagation();
				}}
				className="flex flex-row"
			>
				<form.AppField
					name="active"
					// validators={{
					//     // We can choose between form-wide and field-specific validators
					//     onChange: ({ value }) =>
					//         value.length > 3
					//             ? undefined
					//             : "Username must be longer than 3 letters",
					// }}
					children={(field) => {
						return (
							<div className="m-2 p-2 flex flex-row">
								<div>
									<Label htmlFor="active">
										<span>Active</span>
									</Label>
								</div>

								<Checkbox
									className="ml-2"
									name={field.name}
									onBlur={field.handleBlur}
									checked={field.state.value}
									onCheckedChange={(e) => field.handleChange(e)}
								/>
							</div>
						);
					}}
				/>
				{!card.inventory && (
					<>
						<form.AppField
							name="age"
							children={(field) => (
								<field.InputField
									label="Age"
									inputType="number"
									required={true}
								/>
							)}
						/>
					</>
				)}
				<div className="mt-7">
					<Button type="submit" onClick={() => form.handleSubmit()}>
						Save Card
					</Button>
				</div>
			</form>
		</div>
	);
}
