"use client";

import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { useToastStore } from "@/lib/stores/toast-store";

export default function OnboardingVideoPage() {
  const router = useRouter();
  const addToast = useToastStore((s) => s.addToast);
  const fileRef = useRef<HTMLInputElement>(null);
  const [video, setVideo] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);

  function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setVideo(file);
    setPreview(URL.createObjectURL(file));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setUploading(true);
    try {
      if (video) {
        const formData = new FormData();
        formData.append("video", video);
        const res = await fetch("/api/onboarding/video", {
          method: "POST",
          body: formData,
        });
        if (!res.ok) throw new Error("Upload failed");
      }
      router.push("/onboarding/rates");
    } catch {
      addToast("error", "Failed to upload video.");
    } finally {
      setUploading(false);
    }
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-8">
        <div className="flex items-center gap-2 text-sm text-text-muted mb-2">
          <span className="bg-primary text-white rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold">3</span>
          <span>Step 3 of 6</span>
        </div>
        <h1 className="text-3xl font-bold text-text">Introduction Video</h1>
        <p className="text-text-muted mt-1">Upload a short introduction video. This step is optional.</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-surface rounded-lg p-6 space-y-5">
        <div
          onClick={() => fileRef.current?.click()}
          className="border-2 border-dashed border-surface-light rounded-lg p-8 text-center cursor-pointer hover:border-primary transition-colors"
        >
          <p className="text-text-muted">Click to select a video</p>
          <p className="text-xs text-text-muted mt-1">MP4, MOV up to 100MB</p>
          <input
            ref={fileRef}
            type="file"
            accept="video/*"
            className="hidden"
            onChange={handleFile}
          />
        </div>

        {preview && (
          <div className="relative">
            <video src={preview} controls className="w-full rounded-lg max-h-64" />
            <button
              type="button"
              onClick={() => { setVideo(null); setPreview(null); }}
              className="absolute top-2 right-2 bg-red-600 text-white rounded-full px-3 py-1 text-xs"
            >
              Remove
            </button>
          </div>
        )}

        <div className="flex justify-between pt-4">
          <button
            type="button"
            onClick={() => router.push("/onboarding/photos")}
            className="text-text-muted hover:text-text transition-colors"
          >
            Back
          </button>
          <button
            type="submit"
            disabled={uploading}
            className="bg-primary hover:bg-primary-dark text-white px-8 py-3 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {uploading ? "Uploading..." : video ? "Next: Rates" : "Skip to Rates"}
          </button>
        </div>
      </form>
    </div>
  );
}
