All files / app/(dashboard)/packages page.tsx

60.69% Statements 261/430
68.88% Branches 31/45
15.38% Functions 2/13
60.69% Lines 261/430

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 5341x                                                         19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x 10x 10x 10x 10x 10x 10x   10x 1x 1x 1x   8x 8x 8x 8x 8x   10x 1x 1x 1x   7x   7x 7x 7x 7x 7x   10x       10x 10x             10x 9x 9x 10x   10x 19x   19x                                   19x                                     19x             19x       19x                                                                                                                                                               19x                                                     19x 10x 10x 10x 10x   10x   9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x   9x 3x 3x 3x 3x 3x   3x 3x 3x   3x 3x 3x   6x 6x 7x 7x 7x 7x 7x   7x 2x   2x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x 7x 7x 7x 7x 7x   7x     7x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 6x     7x 4x 4x 6x 6x 6x 6x 4x 4x     7x 1x   7x 7x   6x 6x       19x 19x 19x 19x 19x 19x   9x 19x 19x   19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x 19x 19x 19x 19x 19x 19x 19x 19x 19x     19x   19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x 19x   19x 19x 19x 19x 19x 19x 19x 19x 19x     19x 19x   19x 19x 19x 19x 19x 19x 19x 19x 19x           19x 19x 19x 19x 19x 19x 19x   19x 19x 19x                                                 19x   19x 19x 19x 19x 19x 19x 19x   19x 19x 19x         9x     9x   19x 19x 19x 19x 19x 19x   19x  
'use client';
 
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2, Plus, Pencil, Trash2, Package, Check, X, IndianRupee } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { createClient } from '@/lib/supabase/client';
import {
  createPackageSchema,
  type CreatePackageInput,
  formatPrice,
} from '@/lib/validations/package';
import { useToast } from '@/hooks/use-toast';
import type { Package as PackageType } from '@/types/database';
 
export default function PackagesPage() {
  const [isLoading, setIsLoading] = useState(true);
  const [packages, setPackages] = useState<PackageType[]>([]);
  const [profileId, setProfileId] = useState<string | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingPackage, setEditingPackage] = useState<PackageType | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [deletingPackageId, setDeletingPackageId] = useState<string | null>(null);
  const [featureInput, setFeatureInput] = useState('');
  const [features, setFeatures] = useState<string[]>([]);
  const router = useRouter();
  const { toast } = useToast();
 
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<CreatePackageInput>({
    resolver: zodResolver(createPackageSchema),
    defaultValues: {
      title: '',
      description: '',
      price: 0,
      currency: 'INR',
      duration: '',
      features: [],
      is_active: true,
      is_featured: false,
      display_order: 0,
    },
  });
 
  useEffect(() => {
    const fetchPackages = async () => {
      try {
        const supabase = createClient();
        const {
          data: { user },
        } = await supabase.auth.getUser();
 
        if (!user) {
          router.push('/login');
          return;
        }
 
        const { data: profile } = await supabase
          .from('profiles')
          .select('id')
          .eq('user_id', user.id)
          .single();
 
        if (!profile) {
          router.push('/onboarding');
          return;
        }
 
        setProfileId(profile.id);
 
        const { data: packagesData, error } = await supabase
          .from('packages')
          .select('*')
          .eq('profile_id', profile.id)
          .order('display_order', { ascending: true });
 
        if (error) {
          throw error;
        }
 
        setPackages(packagesData || []);
      } catch (error) {
        console.error('Error fetching packages:', error);
        toast({
          variant: 'destructive',
          title: 'Error',
          description: 'Failed to load packages.',
        });
      } finally {
        setIsLoading(false);
      }
    };
 
    fetchPackages();
  }, [router, toast]);
 
  const openCreateDialog = () => {
    setEditingPackage(null);
    setFeatures([]);
    setFeatureInput('');
    reset({
      title: '',
      description: '',
      price: 0,
      currency: 'INR',
      duration: '',
      features: [],
      is_active: true,
      is_featured: false,
      display_order: packages.length,
    });
    setIsDialogOpen(true);
  };
 
  const openEditDialog = (pkg: PackageType) => {
    setEditingPackage(pkg);
    const pkgFeatures = Array.isArray(pkg.features) ? (pkg.features as string[]) : [];
    setFeatures(pkgFeatures);
    setFeatureInput('');
    reset({
      title: pkg.title,
      description: pkg.description || '',
      price: pkg.price,
      currency: 'INR',
      duration: pkg.duration || '',
      features: pkgFeatures,
      is_active: pkg.is_active,
      is_featured: pkg.is_featured,
      display_order: pkg.display_order,
    });
    setIsDialogOpen(true);
  };
 
  const addFeature = () => {
    if (featureInput.trim() && features.length < 10) {
      setFeatures((prev) => [...prev, featureInput.trim()]);
      setFeatureInput('');
    }
  };
 
  const removeFeature = (index: number) => {
    setFeatures((prev) => prev.filter((_, i) => i !== index));
  };
 
  const onSubmit = async (data: CreatePackageInput) => {
    if (!profileId) return;
 
    setIsSubmitting(true);
    try {
      const supabase = createClient();
 
      const packageData = {
        title: data.title,
        description: data.description || null,
        price: data.price,
        currency: 'INR',
        duration: data.duration || null,
        features: features,
        is_active: data.is_active ?? true,
        is_featured: data.is_featured ?? false,
        display_order: data.display_order ?? 0,
      };
 
      if (editingPackage) {
        // Update existing package
        const { error } = await supabase
          .from('packages')
          .update({
            ...packageData,
            updated_at: new Date().toISOString(),
          })
          .eq('id', editingPackage.id);
 
        if (error) throw error;
 
        setPackages((prev) =>
          prev.map((p) =>
            p.id === editingPackage.id
              ? {
                  ...p,
                  ...packageData,
                }
              : p
          )
        );
 
        toast({
          title: 'Package Updated',
          description: 'Your service package has been updated.',
        });
      } else {
        // Create new package
        const { data: newPackage, error } = await supabase
          .from('packages')
          .insert({
            profile_id: profileId,
            ...packageData,
          })
          .select()
          .single();
 
        if (error) throw error;
 
        setPackages((prev) => [...prev, newPackage]);
 
        toast({
          title: 'Package Added',
          description: 'Your service package has been added.',
        });
      }
 
      setIsDialogOpen(false);
    } catch (error) {
      console.error('Error saving package:', error);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to save package. Please try again.',
      });
    } finally {
      setIsSubmitting(false);
    }
  };
 
  const deletePackage = async (packageId: string) => {
    setDeletingPackageId(packageId);
    try {
      const supabase = createClient();
 
      const { error } = await supabase.from('packages').delete().eq('id', packageId);
 
      if (error) throw error;
 
      setPackages((prev) => prev.filter((p) => p.id !== packageId));
 
      toast({
        title: 'Package Deleted',
        description: 'Your service package has been removed.',
      });
    } catch (error) {
      console.error('Error deleting package:', error);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to delete package. Please try again.',
      });
    } finally {
      setDeletingPackageId(null);
    }
  };
 
  if (isLoading) {
    return (
      <div className="flex min-h-[400px] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }
 
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Service Packages</h1>
          <p className="text-muted-foreground">Create and manage your service offerings</p>
        </div>
        <Button onClick={openCreateDialog}>
          <Plus className="mr-2 h-4 w-4" />
          Add Package
        </Button>
      </div>
 
      {packages.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Package className="mb-4 h-12 w-12 text-muted-foreground" />
            <h3 className="mb-2 text-lg font-medium">No packages yet</h3>
            <p className="mb-4 text-center text-muted-foreground">
              Create service packages to let clients know what you offer.
            </p>
            <Button onClick={openCreateDialog}>
              <Plus className="mr-2 h-4 w-4" />
              Create Your First Package
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {packages.map((pkg) => {
            const pkgFeatures = Array.isArray(pkg.features) ? (pkg.features as string[]) : [];
            return (
              <Card
                key={pkg.id}
                className={`group relative ${pkg.is_featured ? 'border-primary' : ''}`}
              >
                {pkg.is_featured && (
                  <div className="absolute -top-3 left-4 rounded-full bg-primary px-3 py-1 text-xs font-medium text-primary-foreground">
                    Featured
                  </div>
                )}
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <div>
                      <CardTitle className="text-lg">{pkg.title}</CardTitle>
                      {pkg.duration && <CardDescription>{pkg.duration}</CardDescription>}
                    </div>
                    <div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8"
                        onClick={() => openEditDialog(pkg)}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-destructive hover:text-destructive"
                        onClick={() => deletePackage(pkg.id)}
                        disabled={deletingPackageId === pkg.id}
                      >
                        {deletingPackageId === pkg.id ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <Trash2 className="h-4 w-4" />
                        )}
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-baseline gap-1">
                    <IndianRupee className="h-5 w-5" />
                    <span className="text-3xl font-bold">
                      {formatPrice(pkg.price, 'INR').replace('₹', '')}
                    </span>
                  </div>
 
                  {pkg.description && (
                    <p className="text-sm text-muted-foreground">{pkg.description}</p>
                  )}
 
                  {pkgFeatures.length > 0 && (
                    <ul className="space-y-2">
                      {pkgFeatures.map((feature, index) => (
                        <li key={index} className="flex items-start gap-2 text-sm">
                          <Check className="mt-0.5 h-4 w-4 shrink-0 text-green-500" />
                          <span>{feature}</span>
                        </li>
                      ))}
                    </ul>
                  )}
 
                  {!pkg.is_active && (
                    <p className="text-xs text-muted-foreground">This package is inactive</p>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
 
      {/* Add/Edit Package Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>{editingPackage ? 'Edit Package' : 'Add Service Package'}</DialogTitle>
            <DialogDescription>
              {editingPackage
                ? 'Update your service package details.'
                : 'Create a new service package for clients.'}
            </DialogDescription>
          </DialogHeader>
 
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="title">Package Title</Label>
              <Input
                id="title"
                {...register('title')}
                placeholder="Basic Website Design"
                disabled={isSubmitting}
              />
              {errors.title && <p className="text-sm text-destructive">{errors.title.message}</p>}
            </div>
 
            <div className="space-y-2">
              <Label htmlFor="description">Description (optional)</Label>
              <Textarea
                id="description"
                {...register('description')}
                placeholder="Perfect for small businesses looking to establish their online presence..."
                rows={3}
                disabled={isSubmitting}
              />
              {errors.description && (
                <p className="text-sm text-destructive">{errors.description.message}</p>
              )}
            </div>
 
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="price">Price (in Paise)</Label>
                <div className="relative">
                  <IndianRupee className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="price"
                    type="number"
                    {...register('price', { valueAsNumber: true })}
                    placeholder="500000"
                    className="pl-9"
                    disabled={isSubmitting}
                  />
                </div>
                {errors.price && <p className="text-sm text-destructive">{errors.price.message}</p>}
                <p className="text-xs text-muted-foreground">
                  Enter amount in paise (e.g., 500000 = Rs 5,000)
                </p>
              </div>
 
              <div className="space-y-2">
                <Label htmlFor="duration">Duration (optional)</Label>
                <Input
                  id="duration"
                  {...register('duration')}
                  placeholder="2 weeks"
                  disabled={isSubmitting}
                />
                {errors.duration && (
                  <p className="text-sm text-destructive">{errors.duration.message}</p>
                )}
              </div>
            </div>
 
            <div className="space-y-2">
              <Label>Features (up to 10)</Label>
              <div className="flex gap-2">
                <Input
                  value={featureInput}
                  onChange={(e) => setFeatureInput(e.target.value)}
                  placeholder="Add a feature..."
                  disabled={isSubmitting || features.length >= 10}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      addFeature();
                    }
                  }}
                />
                <Button
                  type="button"
                  variant="outline"
                  onClick={addFeature}
                  disabled={isSubmitting || !featureInput.trim() || features.length >= 10}
                >
                  Add
                </Button>
              </div>
              {features.length > 0 && (
                <ul className="mt-2 space-y-1">
                  {features.map((feature, index) => (
                    <li
                      key={index}
                      className="flex items-center justify-between rounded-md bg-muted px-3 py-2 text-sm"
                    >
                      <div className="flex items-center gap-2">
                        <Check className="h-4 w-4 text-green-500" />
                        <span>{feature}</span>
                      </div>
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6"
                        onClick={() => removeFeature(index)}
                        disabled={isSubmitting}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </li>
                  ))}
                </ul>
              )}
            </div>
 
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Loading...
                  </>
                ) : editingPackage ? (
                  'Update Package'
                ) : (
                  'Add Package'
                )}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}