'use client';

import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { Plus, Link as LinkIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Progress } from '@/components/ui/progress';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { cn } from '@/lib/utils';
import Link from 'next/link';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { getUserRepository, GithubRepository } from '@/actions/github/repository';
import { signOut, useSession } from 'next-auth/react';

export const ServiceProviderList = [
	{
		name: 'GitHub',
		value: 'github',
		image: 'https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png',
		permission: 'https://github.com/apps/stalin-deploy/installations/new',
	},
	{
		name: 'Registry',
		value: 'registry',
		image: '',
	},
	{
		name: 'Github Registry',
		value: 'github-registry',
		image: 'https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png',
	},
];

export type NewApplication = {
	serviceProvider: string;
	git: {
		repositoryId: number;
		repositoryName: string;
	};
	env: {
		[key: string]: string;
	};
};

export default function CreateApplicationForm() {
	const [steps, setSteps] = useState(1);

	const [serviceProvider, setServiceProvider] = useState<string>('github');
	const [repositories, setRepositories] = useState<GithubRepository[]>([]);

	const [newApplication, setNewApplication] = useState<NewApplication>({
		serviceProvider: '',
		git: {
			repositoryId: 0,
			repositoryName: '',
		},
		env: {},
	});

	const { data: session } = useSession();
	console.log('user', session);

	useEffect(() => {
		async function fetchRepositories() {
			if (serviceProvider == 'github') {
				const repos = await getUserRepository(session?.user.id as string, session?.user.username as string);
				console.log(session?.user.username as string, repos);
				setRepositories(repos);
			}
		}

		fetchRepositories();
	}, [serviceProvider, session]);

	return (
		<Sheet>
			<SheetTrigger asChild>
				<Button className="flex gap-1 justify-center items-center bg-[#3A7BFE]">
					<Plus />
					New Application
				</Button>
			</SheetTrigger>
			<SheetContent className="min-w-[500px]">
				<SheetHeader>
					<SheetTitle className="text-2xl">New Application</SheetTitle>
					<SheetDescription>Deploy a new application from source</SheetDescription>
				</SheetHeader>
				<div className="flex flex-col">
					<div className="flex flex-col gap-2 my-6">
						<div className="flex flex-row justify-between">
							<p>
								Step: <span className="text-muted-foreground">{(steps == 1 && 'Select Provider') || (steps == 2 && 'Resources') || (steps == 3 && 'Environment Variables') || (steps == 4 && 'Information') || (steps == 5 && 'Review')}</span>
							</p>
							<p>{steps} / 5</p>
						</div>
						<Progress className="bg-gray-300 h-3 " color="red" value={steps * 20} max={100} indicatorColor="bg-[#3A7BFE]" />
					</div>
					<div>
						{steps == 1 && (
							<div>
								<RadioGroup defaultValue="github" className="flex flex-col gap-2 mb-4" onValueChange={setServiceProvider}>
									{ServiceProviderList.map((provider) => (
										<div key={provider.value} className={cn('flex flex-row items-center gap-4 border-[1px] rounded-lg py-2 px-4', provider.value == serviceProvider ? 'border-[#3A7BFE]' : 'border-gray-300')}>
											<RadioGroupItem value={provider.value} id={provider.value} />
											<label htmlFor={provider.value} className="flex flex-row items-center gap-4">
												<img src={provider.image} alt={provider.name} className="w-8 h-8 rounded-full" />
												{provider.name}
											</label>
										</div>
									))}
								</RadioGroup>
								<div className="my-2">
									{serviceProvider == 'github' && (
										<Select onValueChange={(e) => setNewApplication((prev) => ({ ...prev, git: { repositoryId: parseInt(e), repositoryName: repositories.find((w) => w.id == parseInt(e))?.full_name as string } }))}>
											<SelectTrigger className="w-full">
												<SelectValue placeholder="Select a repository" />
											</SelectTrigger>
											<SelectContent>
												<SelectGroup>
													{/* <SelectItem value="1">Repository 1</SelectItem> */}
													{repositories?.map((repository) => (
														<SelectItem key={repository.id} value={repository.id.toString()}>
															{repository.full_name}
														</SelectItem>
													))}
												</SelectGroup>
											</SelectContent>
										</Select>
									)}
								</div>
								{(serviceProvider == 'github' || serviceProvider == 'github-registry') && (
									<p className="text-sm">
										<span className="text-muted-foreground">Not seeing the repositories you expected here?</span> <Link href={ServiceProviderList.find((s) => s.value == serviceProvider)?.permission || ''}>Edit Your GitHub Permissions</Link>
									</p>
								)}
							</div>
						)}
					</div>
					<div className="flex flex-row justify-between my-6">
						<Button
							variant={'outline'}
							className={cn(steps == 1 && 'opacity-0 pointer-events-none select-none')}
							onClick={() => {
								setSteps((prev) => (prev - 1 < 1 ? 1 : prev - 1));
							}}
						>
							Back
						</Button>
						<Button
							className="bg-[#3A7BFE]"
							onClick={() => {
								setSteps((prev) => (prev + 1 > 5 ? 5 : prev + 1));
								console.log(newApplication);
							}}
						>
							{steps == 5 ? 'Deploy' : 'Next'}
						</Button>
					</div>
				</div>
			</SheetContent>
		</Sheet>
	);
}
