'use client';

import './style.scss';
import { useEffect, useState } from 'react';
import { Copy } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

type Props = {
	isEnable: boolean;
	open: boolean;
	onChange: (open: boolean) => void;
}

export default function Copied({ isEnable, open, onChange }: Props) {
	const [url, setUrl] = useState<string>('');

	useEffect(() => {
		if (typeof window !== 'undefined') {
			setUrl(window.location.href);
		}
	}, []);

	if (!isEnable) {
		return;
	}

	const handleCopy = async () => {
		try {
			await navigator.clipboard.writeText(url);
			alert("주소가 복사되었습니다.");
			onChange(false);
		} catch (err) {
			console.error("복사 실패:", err);
		}
	};

	return (
		<Dialog open={open} onOpenChange={onChange}>
			<DialogContent className='sm:max-w-md'>
				<DialogHeader>
					<DialogTitle>주소 복사</DialogTitle>
					<DialogDescription>
						이 주소를 복사하여 다른 곳에 붙여넣기 하세요.
					</DialogDescription>
				</DialogHeader>
				<div className='flex items-center space-x-2'>
					<div className='grid flex-1 gap-2'>
						<Label htmlFor='link' className='sr-only'>
							Link
						</Label>
						<Input id='link' defaultValue={url} readOnly />
					</div>
					<Button type='submit' size='sm' className='px-3' onClick={handleCopy}>
						<span className='sr-only'>Copy</span>
						<Copy />
					</Button>
				</div>
			</DialogContent>
		</Dialog>
	);
}