'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 { getRepositoryBranches, getUserRepository, GithubRepository } from '@/actions/github/repository';
import { signOut, useSession } from 'next-auth/react';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { createApplication, NewApplication } from '@/actions/deploy/application';
import { useParams, useRouter } from 'next/navigation';

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 default function CreateApplicationForm() {
	const [steps, setSteps] = useState(1);
	const [open, setOpen] = useState(false);

	const params = useParams();

	const [repositories, setRepositories] = useState<GithubRepository[]>([]);
	const [branches, setBranches] = useState<string[]>([]);

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

	const { data: session } = useSession();

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

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

	useEffect(() => {
		async function fetchBranches() {
			if (newApplication.serviceProvider == 'github' && newApplication.git.repositoryId != 0) {
				const branches = await getRepositoryBranches(session?.user.id as string, session?.user.username as string, newApplication.git.repositoryName);
				setBranches(branches);
			}
		}
		fetchBranches();
	}, [newApplication.serviceProvider, newApplication.git.repositoryId, newApplication.git.repositoryName, session]);

	return (
		<Sheet open={open} onOpenChange={() => setOpen((open) => !open)}>
			<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={newApplication.serviceProvider || 'github'} className="flex flex-col gap-2 mb-4" onValueChange={(e) => setNewApplication((prev) => ({ ...prev, serviceProvider: e }))}>
									{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 == newApplication.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 flex flex-col gap-2">
									{newApplication.serviceProvider == 'github' && !!repositories && (
										<div>
											<p className="text-muted-foreground text-sm">Repository</p>
											<Select defaultValue={newApplication.git.repositoryId.toString() || ''} onValueChange={(e) => setNewApplication((prev) => ({ ...prev, git: { ...prev.git, repositoryId: parseInt(e), repositoryName: repositories.find((w) => w.id == parseInt(e))?.name as string } }))}>
												<SelectTrigger className="w-full">
													<SelectValue placeholder="Select a repository" />
												</SelectTrigger>
												<SelectContent>
													<SelectGroup>
														{repositories?.map((repository) => (
															<SelectItem key={repository.id} value={repository.id.toString()}>
																{repository.full_name}
															</SelectItem>
														))}
													</SelectGroup>
												</SelectContent>
											</Select>
										</div>
									)}
									{newApplication.serviceProvider == 'github' && newApplication.git.repositoryId != 0 && (
										<>
											<div>
												<p className="text-muted-foreground text-sm">Branch</p>
												<Select onValueChange={(e) => setNewApplication((prev) => ({ ...prev, git: { ...prev.git, branch: e } }))} defaultValue={newApplication.git.branch}>
													<SelectTrigger>
														<SelectValue placeholder="Select a branch" />
													</SelectTrigger>
													<SelectContent>
														{branches.map((branch) => (
															<SelectItem key={branch} value={branch}>
																{branch}
															</SelectItem>
														))}
													</SelectContent>
												</Select>
											</div>
											<div>
												<p className="text-muted-foreground text-sm">Path</p>
												<Input placeholder="Path" value={newApplication.git.path} onChange={(e) => setNewApplication((prev) => ({ ...prev, git: { ...prev.git, path: e.target.value } }))} />
											</div>
											<div>
												<div className={cn('flex flex-row items-center gap-4 border-[1px] rounded-lg py-2 px-4', newApplication.autodeploy ? 'border-[#3A7BFE]' : 'border-gray-300')} onClick={() => setNewApplication((prev) => ({ ...prev, autodeploy: !prev.autodeploy }))}>
													<Checkbox
														checked={newApplication.autodeploy}
														onChange={(e) => {
															console.log(e);
														}}
														id={'autodeploy'}
														color="bg-[#3A7BFE]"
													/>
													<div>
														<label htmlFor="autodeploy" className="text-sm">
															Auto Deploy
														</label>
														<p className="text-xs text-muted-foreground">Every time an update is made to this branch, your application will be re-deployed.</p>
													</div>
												</div>
											</div>
										</>
									)}
								</div>
								{newApplication.serviceProvider == 'github' &&
									(!repositories ? (
										<p className="text-sm">
											<span className="text-muted-foreground">We don&apos;t have access to your repositories.</span> <Link href={ServiceProviderList.find((s) => s.value == newApplication.serviceProvider)?.permission || ''}>Link your GitHub account</Link>
										</p>
									) : (
										<p className="text-sm">
											<span className="text-muted-foreground">Not seeing the repositories you expected here?</span> <Link href={ServiceProviderList.find((s) => s.value == newApplication.serviceProvider)?.permission || ''}>Edit Your GitHub Permissions</Link>
										</p>
									))}
							</div>
						)}

						{steps == 2 && (
							<div>
								<p>Resources WIP</p>
								<p>For now 1 vCPU & 1024Mb RAM</p>
							</div>
						)}

						{steps == 3 && (
							<div>
								<p>Environment Variables WIP</p>
							</div>
						)}

						{steps == 4 && (
							<div>
								<p className="text-muted-foreground text-sm">Application Name</p>
								<Input placeholder="App Name" value={newApplication.name} onChange={(e) => setNewApplication((prev) => ({ ...prev, name: e.target.value }))} />
							</div>
						)}

						{steps == 5 && (
							<div>
								<div className="flex flex-col gap-2">
									<div>
										<p className="text-muted-foreground text-sm">Service Provider</p>
										<p>{newApplication.serviceProvider}</p>
									</div>
									<div>
										<p className="text-muted-foreground text-sm">Repository</p>
										<p>{newApplication.git.repositoryName}</p>
									</div>
									<div>
										<p className="text-muted-foreground text-sm">Branch</p>
										<p>{newApplication.git.branch}</p>
									</div>
									<div>
										<p className="text-muted-foreground text-sm">Path</p>
										<p>{newApplication.git.path}</p>
									</div>
									<div>
										<p className="text-muted-foreground text-sm">Auto Deploy</p>
										<p>{newApplication.autodeploy ? 'Enabled' : 'Disabled'}</p>
									</div>
									<div>
										<p className="text-muted-foreground text-sm">Application Name</p>
										<p>{newApplication.name}</p>
									</div>
								</div>
							</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>
						{steps == 5 ? (
							<Button
								className="bg-[#3A7BFE]"
								onClick={async () => {
									const app = await createApplication(newApplication, params.workspace as string);
									console.log(app);
									setOpen(false);
									setNewApplication({
										serviceProvider: 'github',
										git: {
											repositoryId: 0,
											repositoryName: '',
											branch: '',
											path: '',
										},
										autodeploy: true,
										env: {},
										name: '',
									});
								}}
							>
								Deploy
							</Button>
						) : (
							<Button
								className="bg-[#3A7BFE]"
								onClick={() => {
									setSteps((prev) => (prev + 1 > 5 ? 5 : prev + 1));
									console.log(newApplication);
								}}
							>
								Next
							</Button>
						)}
					</div>
				</div>
			</SheetContent>
		</Sheet>
	);
}
