Initial commit

This commit is contained in:
twotalesanimation
2026-05-19 22:20:29 +02:00
commit 0fbe856dce
173 changed files with 38316 additions and 0 deletions
+287
View File
@@ -0,0 +1,287 @@
"use client";
import { useState, useRef } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { importShotsFromCsv } from "@/actions/shots";
import { useToast } from "@/components/ui/use-toast";
import { Upload, AlertCircle, CheckCircle2, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
interface ParsedRow {
scene: string;
episode?: string;
description?: string;
priority?: string;
fps?: number;
frameStart?: number;
frameEnd?: number;
}
interface ImportShotsDialogProps {
projectId: string;
projectType?: "STANDARD" | "EPISODIC";
open: boolean;
onClose: () => void;
onSuccess?: () => void;
}
const TEMPLATE_STANDARD = `scene,description,priority,fps,frameStart,frameEnd
010,Opening wide shot,NORMAL,24,1001,1100
020,Close up reaction,NORMAL,24,,
030,Action sequence,HIGH,24,1001,1250`;
const TEMPLATE_EPISODIC = `scene,episode,description,priority,fps,frameStart,frameEnd
010,EP01,Opening wide shot,NORMAL,24,1001,1100
020,EP01,Close up reaction,NORMAL,24,,
010,EP02,Act two opener,HIGH,24,1001,1200`;
function parseCsv(raw: string): { rows: ParsedRow[]; parseErrors: string[] } {
const lines = raw.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
if (lines.length < 2) return { rows: [], parseErrors: ["Need at least a header row and one data row"] };
const headers = lines[0].split(",").map((h) => h.trim().toLowerCase());
const sceneIdx = headers.indexOf("scene");
if (sceneIdx === -1) return { rows: [], parseErrors: ['Missing required "scene" column'] };
const idx = (name: string) => {
const i = headers.indexOf(name);
return i === -1 ? null : i;
};
const rows: ParsedRow[] = [];
const parseErrors: string[] = [];
for (let i = 1; i < lines.length; i++) {
const cells = lines[i].split(",").map((c) => c.trim());
const get = (name: string) => {
const j = idx(name);
return j !== null ? cells[j] ?? "" : "";
};
const scene = get("scene");
if (!scene) { parseErrors.push(`Row ${i + 1}: empty scene — skipped`); continue; }
const fpsRaw = get("fps");
const fsRaw = get("framestart") || get("frameStart");
const feRaw = get("frameend") || get("frameEnd");
rows.push({
scene,
episode: get("episode") || undefined,
description: get("description") || undefined,
priority: get("priority") || undefined,
fps: fpsRaw ? Number(fpsRaw) : undefined,
frameStart: fsRaw ? Number(fsRaw) : undefined,
frameEnd: feRaw ? Number(feRaw) : undefined,
});
}
return { rows, parseErrors };
}
export function ImportShotsDialog({
projectId,
projectType = "STANDARD",
open,
onClose,
onSuccess,
}: ImportShotsDialogProps) {
const { toast } = useToast();
const [step, setStep] = useState<"input" | "preview">("input");
const [csvText, setCsvText] = useState("");
const [parsedRows, setParsedRows] = useState<ParsedRow[]>([]);
const [parseErrors, setParseErrors] = useState<string[]>([]);
const [isImporting, setIsImporting] = useState(false);
const [importResult, setImportResult] = useState<{ created: string[]; errors: string[] } | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => setCsvText(ev.target?.result as string ?? "");
reader.readAsText(file);
};
const handleParse = () => {
const { rows, parseErrors: errs } = parseCsv(csvText);
setParsedRows(rows);
setParseErrors(errs);
if (rows.length > 0) setStep("preview");
};
const handleImport = async () => {
setIsImporting(true);
try {
const result = await importShotsFromCsv(projectId, parsedRows);
setImportResult(result);
if (result.created.length > 0) {
toast({ title: `${result.created.length} shot${result.created.length === 1 ? "" : "s"} created` });
onSuccess?.();
}
} catch (e) {
toast({ title: "Import failed", description: e instanceof Error ? e.message : undefined, variant: "destructive" });
} finally {
setIsImporting(false);
}
};
const handleClose = () => {
setStep("input");
setCsvText("");
setParsedRows([]);
setParseErrors([]);
setImportResult(null);
onClose();
};
const template = projectType === "EPISODIC" ? TEMPLATE_EPISODIC : TEMPLATE_STANDARD;
return (
<Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
<DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Import Shots from CSV</DialogTitle>
</DialogHeader>
{importResult ? (
/* Result screen */
<div className="space-y-4 py-2">
{importResult.created.length > 0 && (
<div className="space-y-1.5">
<p className="flex items-center gap-2 text-sm font-medium text-emerald-400">
<CheckCircle2 className="h-4 w-4" />
{importResult.created.length} shot{importResult.created.length === 1 ? "" : "s"} created
</p>
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-3 text-xs font-mono text-zinc-300 max-h-40 overflow-y-auto">
{importResult.created.map((code) => <div key={code}>{code}</div>)}
</div>
</div>
)}
{importResult.errors.length > 0 && (
<div className="space-y-1.5">
<p className="flex items-center gap-2 text-sm font-medium text-amber-400">
<AlertCircle className="h-4 w-4" />
{importResult.errors.length} warning{importResult.errors.length === 1 ? "" : "s"}
</p>
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-3 text-xs text-zinc-400 max-h-32 overflow-y-auto space-y-0.5">
{importResult.errors.map((e, i) => <div key={i}>{e}</div>)}
</div>
</div>
)}
<DialogFooter>
<Button onClick={handleClose}>Done</Button>
</DialogFooter>
</div>
) : step === "input" ? (
/* CSV input step */
<div className="space-y-4 py-2">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Paste CSV or upload a file. Required column: <code className="text-xs bg-zinc-800 px-1 rounded">scene</code>.
{projectType === "EPISODIC" && (
<> Also required: <code className="text-xs bg-zinc-800 px-1 rounded">episode</code>.</>
)}
</p>
<Button
type="button"
variant="outline"
size="sm"
className="gap-1.5 shrink-0"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="h-3.5 w-3.5" />
Upload file
</Button>
<input ref={fileInputRef} type="file" accept=".csv,text/csv" className="hidden" onChange={handleFileUpload} />
</div>
<Textarea
value={csvText}
onChange={(e) => setCsvText(e.target.value)}
className="font-mono text-xs min-h-[180px]"
placeholder={template}
spellCheck={false}
/>
{parseErrors.length > 0 && (
<div className="text-xs text-amber-400 space-y-0.5">
{parseErrors.map((e, i) => <div key={i} className="flex items-start gap-1.5"><AlertCircle className="h-3 w-3 mt-0.5 shrink-0" />{e}</div>)}
</div>
)}
<details className="text-xs text-zinc-500 cursor-pointer">
<summary className="hover:text-zinc-300 transition-colors">CSV format & example</summary>
<pre className="mt-2 bg-zinc-900 border border-zinc-800 rounded p-3 text-zinc-400 whitespace-pre-wrap">{template}</pre>
</details>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>Cancel</Button>
<Button onClick={handleParse} disabled={!csvText.trim()} className="gap-1.5">
Parse
<ChevronRight className="h-4 w-4" />
</Button>
</DialogFooter>
</div>
) : (
/* Preview step */
<div className="space-y-4 py-2">
<p className="text-sm text-muted-foreground">
{parsedRows.length} shot{parsedRows.length === 1 ? "" : "s"} ready to import. Review and confirm.
</p>
<div className="rounded-lg border border-zinc-800 overflow-hidden">
<table className="w-full text-xs">
<thead className="bg-zinc-900 text-zinc-400">
<tr>
<th className="px-3 py-2 text-left font-medium">Scene</th>
{projectType === "EPISODIC" && <th className="px-3 py-2 text-left font-medium">Episode</th>}
<th className="px-3 py-2 text-left font-medium">Description</th>
<th className="px-3 py-2 text-left font-medium">Priority</th>
<th className="px-3 py-2 text-left font-medium">FPS</th>
<th className="px-3 py-2 text-left font-medium">Frames</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-800">
{parsedRows.map((row, i) => (
<tr key={i} className={cn("bg-zinc-950", i % 2 === 0 && "bg-zinc-900/30")}>
<td className="px-3 py-2 font-mono text-zinc-200">{row.scene}</td>
{projectType === "EPISODIC" && <td className="px-3 py-2 font-mono text-zinc-400">{row.episode ?? "—"}</td>}
<td className="px-3 py-2 text-zinc-400 truncate max-w-[160px]">{row.description ?? "—"}</td>
<td className="px-3 py-2 text-zinc-400">{row.priority ?? "NORMAL"}</td>
<td className="px-3 py-2 text-zinc-400">{row.fps ?? 24}</td>
<td className="px-3 py-2 text-zinc-400 font-mono">
{row.frameStart || row.frameEnd ? `${row.frameStart ?? "?"}${row.frameEnd ?? "?"}` : "—"}
</td>
</tr>
))}
</tbody>
</table>
</div>
{parseErrors.length > 0 && (
<div className="text-xs text-amber-400 space-y-0.5">
{parseErrors.map((e, i) => <div key={i} className="flex items-start gap-1.5"><AlertCircle className="h-3 w-3 mt-0.5 shrink-0" />{e}</div>)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setStep("input")}>Back</Button>
<Button onClick={handleImport} disabled={isImporting || parsedRows.length === 0}>
{isImporting ? "Importing…" : `Import ${parsedRows.length} Shot${parsedRows.length === 1 ? "" : "s"}`}
</Button>
</DialogFooter>
</div>
)}
</DialogContent>
</Dialog>
);
}
+236
View File
@@ -0,0 +1,236 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { createShot } from "@/actions/shots";
import { useToast } from "@/components/ui/use-toast";
const shotSchema = z.object({
scene: z.string().min(1, "Scene is required").max(50).regex(/^[A-Z0-9_]+$/i, "Alphanumeric and underscore only"),
episode: z.string().max(50).optional(),
description: z.string().optional(),
priority: z.enum(["LOW", "NORMAL", "HIGH", "URGENT"]),
fps: z.coerce.number().min(1).max(120),
});
type ShotFormValues = z.infer<typeof shotSchema>;
interface NewShotDialogProps {
projectId: string;
projectType?: "STANDARD" | "EPISODIC";
open: boolean;
onClose: () => void;
onSuccess?: () => void;
}
export function NewShotDialog({ projectId, projectType = "STANDARD", open, onClose, onSuccess }: NewShotDialogProps) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [thumbnailFile, setThumbnailFile] = useState<File | null>(null);
const [thumbnailPreview, setThumbnailPreview] = useState<string | null>(null);
const { toast } = useToast();
const router = useRouter();
const isEpisodic = projectType === "EPISODIC";
const {
register,
handleSubmit,
setValue,
reset,
formState: { errors },
} = useForm<ShotFormValues>({
resolver: zodResolver(shotSchema),
defaultValues: { priority: "NORMAL", fps: 24 },
});
const handleThumbnailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setThumbnailFile(file);
const reader = new FileReader();
reader.onload = (event) => {
setThumbnailPreview(event.target?.result as string);
};
reader.readAsDataURL(file);
}
};
const onSubmit = async (data: ShotFormValues) => {
setIsSubmitting(true);
try {
let thumbnailUrl: string | undefined;
// Upload thumbnail if provided
if (thumbnailFile) {
const formData = new FormData();
formData.append("file", thumbnailFile);
formData.append("type", "image");
const uploadRes = await fetch("/api/upload", {
method: "POST",
body: formData,
});
if (!uploadRes.ok) {
throw new Error("Failed to upload thumbnail");
}
const uploadData = await uploadRes.json();
thumbnailUrl = uploadData.url;
}
await createShot({ projectId, ...data, thumbnailUrl });
toast({ title: "Shot created" });
reset();
setThumbnailFile(null);
setThumbnailPreview(null);
router.refresh();
onSuccess?.();
onClose();
} catch (err) {
toast({
title: "Failed to create shot",
description: (err as Error).message,
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>New Shot</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className={`grid gap-3 ${isEpisodic ? "grid-cols-2" : "grid-cols-1"}`}>
{isEpisodic && (
<div className="space-y-1.5">
<Label htmlFor="episode">Episode *</Label>
<Input
id="episode"
placeholder="EP01"
{...register("episode")}
className="uppercase"
/>
{errors.episode && (
<p className="text-xs text-destructive">{errors.episode.message}</p>
)}
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="scene">Scene *</Label>
<Input
id="scene"
placeholder="SC010"
{...register("scene")}
className="uppercase"
/>
{errors.scene && (
<p className="text-xs text-destructive">{errors.scene.message}</p>
)}
</div>
</div>
<p className="text-xs text-muted-foreground">
Shot code will be auto-generated (e.g.{" "}
{isEpisodic ? "SHOW_EP01_SC010_0010" : "SHOW_SC010_0010"})
</p>
<div className="space-y-1.5">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
placeholder="What happens in this shot?"
{...register("description")}
className="min-h-[70px]"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="thumbnail">Thumbnail (optional)</Label>
<Input
id="thumbnail"
type="file"
accept="image/*"
onChange={handleThumbnailChange}
className="cursor-pointer"
/>
{thumbnailPreview && (
<div className="relative w-full aspect-[2.39] rounded-lg overflow-hidden border border-border">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={thumbnailPreview}
alt="Thumbnail preview"
className="w-full h-full object-cover"
/>
</div>
)}
</div>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-1.5 col-span-2">
<Label>Priority</Label>
<Select
defaultValue="NORMAL"
onValueChange={(v) => setValue("priority", v as any)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="LOW">Low</SelectItem>
<SelectItem value="NORMAL">Normal</SelectItem>
<SelectItem value="HIGH">High</SelectItem>
<SelectItem value="URGENT">Urgent</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="fps">FPS</Label>
<Input
id="fps"
type="number"
placeholder="24"
{...register("fps")}
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Creating..." : "Create Shot"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
+206
View File
@@ -0,0 +1,206 @@
"use client";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { getInitials, formatRelativeDate } from "@/lib/utils";
import {
MoreHorizontal,
Film,
MessageSquare,
Clock,
CheckCircle2,
AlertCircle,
ArrowUpRight,
} from "lucide-react";
import type { ShotWithDetails } from "@/types";
interface ShotCardProps {
shot: ShotWithDetails;
projectId: string;
compact?: boolean;
}
const STATUS_CONFIG: Record<
string,
{ label: string; color: string; icon: React.ElementType }
> = {
WAITING: { label: "Waiting", color: "bg-zinc-500/10 text-zinc-400 border-zinc-500/20", icon: Clock },
IN_PROGRESS: { label: "In Progress", color: "bg-blue-500/10 text-blue-400 border-blue-500/20", icon: Film },
IN_REVIEW: { label: "In Review", color: "bg-purple-500/10 text-purple-400 border-purple-500/20", icon: AlertCircle },
REVISIONS: { label: "Revisions", color: "bg-orange-500/10 text-orange-400 border-orange-500/20", icon: AlertCircle },
COMPLETE: { label: "Complete", color: "bg-emerald-500/10 text-emerald-400 border-emerald-500/20", icon: CheckCircle2 },
};
const PRIORITY_DOT: Record<string, string> = {
LOW: "bg-zinc-500",
NORMAL: "bg-blue-500",
HIGH: "bg-amber-500",
URGENT: "bg-red-500",
};
export function ShotCard({ shot, projectId, compact = false }: ShotCardProps) {
const router = useRouter();
const statusCfg = STATUS_CONFIG[shot.status] ?? STATUS_CONFIG.WAITING;
const StatusIcon = statusCfg.icon;
const latestVersion = shot.versions?.[0];
const openComments = shot.versions
?.reduce((sum, v) => sum + (v._count?.comments ?? 0), 0) ?? 0;
if (compact) {
return (
<div className="flex items-center gap-3 px-3 py-2.5 rounded-lg border border-border hover:border-border/80 transition-colors group">
<div
className={cn("w-2 h-2 rounded-full shrink-0", PRIORITY_DOT[shot.priority] ?? "bg-zinc-500")}
title={shot.priority}
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-mono text-xs text-muted-foreground">{shot.shotCode}</span>
{shot.sequence && (
<span className="text-xs text-muted-foreground/60">{shot.sequence}</span>
)}
</div>
{shot.description && (
<p className="text-sm truncate text-foreground/80 mt-0.5">{shot.description}</p>
)}
</div>
<span className={cn("text-xs px-1.5 py-0.5 rounded border", statusCfg.color)}>
{statusCfg.label}
</span>
<Link href={`/projects/${projectId}/shots/${shot.id}`}>
<Button variant="ghost" size="icon-sm" className="opacity-0 group-hover:opacity-100 transition-opacity">
<ArrowUpRight className="h-3.5 w-3.5" />
</Button>
</Link>
</div>
);
}
return (
<Card className="group hover:border-border/80 transition-colors">
<CardHeader className="pb-2">
{/* Thumbnail with cinema scope aspect ratio (2.39:1) */}
<div className="mb-3 -mx-6 -mt-6 overflow-hidden rounded-t-lg">
<div className="relative w-full aspect-[2.39]">
{shot.thumbnailUrl || latestVersion?.thumbnailUrl || latestVersion?.posterUrl ? (
<Image
src={shot.thumbnailUrl || latestVersion?.thumbnailUrl || latestVersion?.posterUrl || ""}
alt={shot.shotCode}
fill
className="object-cover"
/>
) : (
<div className="w-full h-full bg-gradient-to-br from-zinc-800 to-zinc-900 flex items-center justify-center">
<div className="text-center">
<Film className="h-12 w-12 text-zinc-600 mx-auto mb-2" />
<p className="font-mono text-lg font-semibold text-zinc-400">{shot.shotCode}</p>
</div>
</div>
)}
</div>
</div>
{/* Header info */}
<div className="flex items-start justify-between gap-2">
<div className="flex items-center gap-2">
<div
className={cn("w-2 h-2 rounded-full mt-0.5", PRIORITY_DOT[shot.priority] ?? "bg-zinc-500")}
title={`Priority: ${shot.priority}`}
/>
<div>
<span className="font-mono text-xs text-muted-foreground">{shot.shotCode}</span>
{shot.sequence && (
<span className="text-xs text-muted-foreground/50 ml-2">{shot.sequence}</span>
)}
</div>
</div>
<div className="flex items-center gap-2">
<span className={cn("text-xs px-2 py-0.5 rounded-full border", statusCfg.color)}>
<StatusIcon className="h-3 w-3 inline mr-1" />
{statusCfg.label}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" className="opacity-100 group-hover:opacity-100 transition-opacity text-muted-foreground">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href={`/projects/${projectId}/shots/${shot.id}`}>
View shot
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{shot.description && (
<p className="text-sm text-foreground/80 line-clamp-2 mt-1">{shot.description}</p>
)}
</CardHeader>
<CardContent className="pb-2">
{/* Stats row */}
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<Film className="h-3.5 w-3.5" />
{shot.versions?.length ?? 0} version{(shot.versions?.length ?? 0) !== 1 ? "s" : ""}
</span>
{openComments > 0 && (
<span className="flex items-center gap-1 text-amber-400">
<MessageSquare className="h-3.5 w-3.5" />
{openComments} open
</span>
)}
{shot.dueDate && (
<span className="flex items-center gap-1 ml-auto">
<Clock className="h-3.5 w-3.5" />
{formatRelativeDate(shot.dueDate)}
</span>
)}
</div>
</CardContent>
<CardFooter className="pt-2 flex items-center justify-between">
{/* Artist avatar */}
{shot.artist ? (
<div className="flex items-center gap-1.5">
<Avatar className="h-5 w-5">
{shot.artist.image && <AvatarImage src={shot.artist.image} />}
<AvatarFallback className="text-[9px]">
{getInitials(shot.artist.name)}
</AvatarFallback>
</Avatar>
<span className="text-xs text-muted-foreground">
{shot.artist.name ?? shot.artist.email}
</span>
</div>
) : (
<span className="text-xs text-muted-foreground">Unassigned</span>
)}
<Button variant="ghost" size="sm" asChild className="text-xs h-7">
<Link href={`/projects/${projectId}/shots/${shot.id}`}>
VIEW
</Link>
</Button>
</CardFooter>
</Card>
);
}
+292
View File
@@ -0,0 +1,292 @@
"use client";
import { useState, useRef } from "react";
import Image from "next/image";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { updateShot } from "@/actions/shots";
import { useToast } from "@/components/ui/use-toast";
import { Upload, X, Film, ImageIcon } from "lucide-react";
const settingsSchema = z.object({
description: z.string().optional(),
status: z.enum(["WAITING", "IN_PROGRESS", "IN_REVIEW", "REVISIONS", "COMPLETE"]),
priority: z.enum(["LOW", "NORMAL", "HIGH", "URGENT"]),
fps: z.coerce.number().min(1).max(240),
frameStart: z.coerce.number().int().optional().or(z.literal("")),
frameEnd: z.coerce.number().int().optional().or(z.literal("")),
dueDate: z.string().optional(),
artistId: z.string().optional(),
});
type SettingsFormValues = z.infer<typeof settingsSchema>;
interface Artist {
id: string;
name: string | null;
email: string;
}
interface ShotSettingsTabProps {
shot: {
id: string;
shotCode: string;
description: string | null;
status: string;
priority: string;
fps: number;
frameStart?: number | null;
frameEnd?: number | null;
dueDate: Date | string | null;
artistId: string | null;
thumbnailUrl: string | null;
};
artists: Artist[];
onSaved?: () => void;
}
export function ShotSettingsTab({ shot, artists, onSaved }: ShotSettingsTabProps) {
const { toast } = useToast();
const [isSaving, setIsSaving] = useState(false);
const [thumbnailFile, setThumbnailFile] = useState<File | null>(null);
const [thumbnailPreview, setThumbnailPreview] = useState<string | null>(shot.thumbnailUrl ?? null);
const [clearThumbnail, setClearThumbnail] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const formatDate = (d: Date | string | null) => {
if (!d) return "";
return new Date(d).toISOString().split("T")[0];
};
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm<SettingsFormValues>({
resolver: zodResolver(settingsSchema),
defaultValues: {
description: shot.description ?? "",
status: shot.status as SettingsFormValues["status"],
priority: shot.priority as SettingsFormValues["priority"],
fps: shot.fps,
frameStart: shot.frameStart ?? "",
frameEnd: shot.frameEnd ?? "",
dueDate: formatDate(shot.dueDate),
artistId: shot.artistId ?? "__none__",
},
});
const handleThumbnailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setThumbnailFile(file);
setClearThumbnail(false);
const reader = new FileReader();
reader.onload = (ev) => setThumbnailPreview(ev.target?.result as string);
reader.readAsDataURL(file);
};
const onSubmit = async (values: SettingsFormValues) => {
setIsSaving(true);
try {
let thumbnailUrl: string | null | undefined = undefined;
if (clearThumbnail) {
thumbnailUrl = null;
} else if (thumbnailFile) {
const fd = new FormData();
fd.append("file", thumbnailFile);
fd.append("type", "image");
const res = await fetch("/api/upload", { method: "POST", body: fd });
if (!res.ok) throw new Error("Thumbnail upload failed");
const data = await res.json();
thumbnailUrl = data.url;
}
await updateShot({
shotId: shot.id,
description: values.description || undefined,
status: values.status,
priority: values.priority,
fps: values.fps,
frameStart: values.frameStart !== "" && values.frameStart != null ? Number(values.frameStart) : null,
frameEnd: values.frameEnd !== "" && values.frameEnd != null ? Number(values.frameEnd) : null,
dueDate: values.dueDate || null,
artistId: values.artistId === "__none__" ? null : values.artistId,
thumbnailUrl,
});
toast({ title: "Shot updated" });
onSaved?.();
} catch (e) {
toast({ title: "Failed to save", description: e instanceof Error ? e.message : undefined, variant: "destructive" });
} finally {
setIsSaving(false);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8 max-w-2xl">
{/* Details */}
<div className="space-y-4">
<div className="flex items-center gap-2 text-sm font-semibold text-zinc-300">
<Film className="h-4 w-4 text-amber-500" />
Details
</div>
<Separator />
<div className="space-y-1.5">
<Label>Description</Label>
<Textarea {...register("description")} rows={3} placeholder="Shot description…" />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label>Status</Label>
<Select
defaultValue={shot.status}
onValueChange={(v) => setValue("status", v as SettingsFormValues["status"])}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="WAITING">Waiting</SelectItem>
<SelectItem value="IN_PROGRESS">In Progress</SelectItem>
<SelectItem value="IN_REVIEW">In Review</SelectItem>
<SelectItem value="REVISIONS">Revisions</SelectItem>
<SelectItem value="COMPLETE">Complete</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Priority</Label>
<Select
defaultValue={shot.priority}
onValueChange={(v) => setValue("priority", v as SettingsFormValues["priority"])}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="LOW">Low</SelectItem>
<SelectItem value="NORMAL">Normal</SelectItem>
<SelectItem value="HIGH">High</SelectItem>
<SelectItem value="CRITICAL">Critical</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Timing */}
<div className="space-y-4">
<div className="flex items-center gap-2 text-sm font-semibold text-zinc-300">
<span className="text-amber-500 font-mono text-xs">FPS</span>
Timing
</div>
<Separator />
<div className="grid grid-cols-3 gap-4">
<div className="space-y-1.5">
<Label>FPS</Label>
<Input type="number" step="any" {...register("fps")} />
{errors.fps && <p className="text-xs text-destructive">{errors.fps.message}</p>}
</div>
<div className="space-y-1.5">
<Label>Frame Start</Label>
<Input type="number" {...register("frameStart")} placeholder="1001" />
</div>
<div className="space-y-1.5">
<Label>Frame End</Label>
<Input type="number" {...register("frameEnd")} placeholder="1100" />
</div>
</div>
<div className="space-y-1.5 max-w-xs">
<Label>Due Date</Label>
<Input type="date" {...register("dueDate")} />
</div>
</div>
{/* Assignment */}
<div className="space-y-4">
<div className="flex items-center gap-2 text-sm font-semibold text-zinc-300">
<span className="text-amber-500">👤</span>
Assignment
</div>
<Separator />
<div className="space-y-1.5 max-w-xs">
<Label>Artist</Label>
<Select
defaultValue={shot.artistId ?? "__none__"}
onValueChange={(v) => setValue("artistId", v)}
>
<SelectTrigger><SelectValue placeholder="Unassigned" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none__">Unassigned</SelectItem>
{artists.map((a) => (
<SelectItem key={a.id} value={a.id}>
{a.name ?? a.email}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Thumbnail */}
<div className="space-y-4">
<div className="flex items-center gap-2 text-sm font-semibold text-zinc-300">
<ImageIcon className="h-4 w-4 text-amber-500" />
Thumbnail
</div>
<Separator />
{thumbnailPreview && !clearThumbnail ? (
<div className="relative w-72 aspect-[2.39] rounded-lg overflow-hidden border border-border group">
<Image src={thumbnailPreview} alt={shot.shotCode} fill className="object-cover" />
<button
type="button"
onClick={() => { setClearThumbnail(true); setThumbnailPreview(null); setThumbnailFile(null); }}
className="absolute top-1.5 right-1.5 bg-black/70 hover:bg-black text-white rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
) : (
<div
onClick={() => fileInputRef.current?.click()}
className="w-72 aspect-[2.39] rounded-lg border-2 border-dashed border-border hover:border-amber-500/50 flex items-center justify-center gap-2 text-sm text-muted-foreground cursor-pointer transition-colors"
>
<Upload className="h-4 w-4" />
Upload thumbnail
</div>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleThumbnailChange}
/>
</div>
<Button type="submit" disabled={isSaving}>
{isSaving ? "Saving…" : "Save Changes"}
</Button>
</form>
);
}