"use client";

import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { useCreateFromDocument } from "@/hooks/use-api";
import { useToast } from "@/components/ui/toast";
import {
  FileText,
  Upload,
  Loader2,
  ArrowRight,
  Sparkles,
  Wand2,
  X,
  File,
} from "lucide-react";
import {
  LanguageSelector,
  StyleSelector,
  DurationSelector,
  AspectRatioSelector,
} from "@/components/projects/ProjectConfiguration";

export default function DocumentToVideoPage() {
  const router = useRouter();
  const { toast } = useToast();
  const createFromDoc = useCreateFromDocument();

  const fileInputRef = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File | null>(null);
  
  const [style, setStyle] = useState("CINEMATIC");
  const [cinematicReference, setCinematicReference] = useState("");
  const [duration, setDuration] = useState(60);
  const [aspectRatio, setAspectRatio] = useState("PORTRAIT_9_16");
  const [language, setLanguage] = useState("tr");

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const selectedFile = e.target.files[0];
      
      // Boyut kontrolü (örn: 10MB)
      if (selectedFile.size > 10 * 1024 * 1024) {
        toast("error", "Dosya boyutu 10MB'dan küçük olmalıdır.");
        return;
      }
      
      setFile(selectedFile);
    }
  };

  const clearFile = () => {
    setFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleGenerate = async () => {
    if (!file) {
      toast("error", "Lütfen bir belge yükleyin.");
      return;
    }

    try {
      const result: any = await createFromDoc.mutateAsync({
        file,
        language,
        aspectRatio,
        videoStyle: style,
        cinematicReference: cinematicReference ? cinematicReference : undefined,
        targetDuration: duration,
      });

      toast("success", "Belge → Video projesi oluşturuldu!");
      router.push(`/dashboard/projects/${result.id}`);
    } catch {
      toast("error", "Proje oluşturulurken bir hata oluştu.");
    }
  };

  return (
    <div className="max-w-3xl mx-auto space-y-8 pb-24">
      {/* Header */}
      <div className="text-center space-y-3 pb-4">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-3xl bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] mb-2 ring-1 ring-[var(--color-bg-inverted)]/20 shadow-none">
          <FileText size={32} />
        </div>
        <h1 className="font-[family-name:var(--font-display)] text-3xl md:text-4xl font-bold tracking-tight text-[var(--color-text-primary)]">
          Belgeden Video Üret
        </h1>
        <p className="text-[var(--color-text-muted)] text-sm max-w-lg mx-auto">
          PDF, Word veya Text dosyalarınızı yükleyin, yapay zeka sizin için profesyonel bir videoya dönüştürsün
        </p>
      </div>

      {/* Main Form */}
      <div className="card p-6 md:p-8 space-y-6">
        
        {/* File Upload */}
        <div>
          <label className="text-sm font-medium text-[var(--color-text-secondary)] mb-2 block">
            Belge Yükle (.pdf, .docx, .txt, vb.)
          </label>
          
          {!file ? (
            <div 
              onClick={() => fileInputRef.current?.click()}
              className="w-full h-32 border-2 border-dashed border-[var(--color-border-default)] rounded-xl flex flex-col items-center justify-center gap-3 bg-[var(--color-bg-surface)] hover:bg-[var(--color-bg-elevated)] transition-colors cursor-pointer"
            >
              <div className="w-10 h-10 rounded-full bg-[var(--color-bg-elevated)] flex items-center justify-center text-[var(--color-text-muted)]">
                <Upload size={20} />
              </div>
              <div className="text-center">
                <p className="text-sm font-medium text-[var(--color-text-primary)]">Tıklayın veya sürükleyin</p>
                <p className="text-xs text-[var(--color-text-ghost)] mt-1">Maksimum 10MB</p>
              </div>
            </div>
          ) : (
            <div className="w-full p-4 border border-[var(--color-border-default)] rounded-xl flex items-center justify-between bg-[var(--color-bg-elevated)]">
              <div className="flex items-center gap-3 overflow-hidden">
                <div className="w-10 h-10 rounded-lg bg-[var(--color-bg-surface)] flex items-center justify-center text-[var(--color-text-secondary)] shrink-0">
                  <File size={20} />
                </div>
                <div className="truncate">
                  <p className="text-sm font-medium text-[var(--color-text-primary)] truncate">{file.name}</p>
                  <p className="text-xs text-[var(--color-text-ghost)]">{(file.size / 1024 / 1024).toFixed(2)} MB</p>
                </div>
              </div>
              <button 
                onClick={clearFile}
                className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--color-bg-surface)] text-[var(--color-text-muted)] transition-colors shrink-0"
              >
                <X size={16} />
              </button>
            </div>
          )}
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileChange}
            accept=".pdf,.doc,.docx,.txt,.csv"
            className="hidden"
          />
        </div>

        {/* Configurations */}
        <div className="space-y-8 pt-6 border-t border-[var(--color-border-faint)]">
          <LanguageSelector value={language} onChange={setLanguage} />
          
          <StyleSelector 
            value={style} 
            onChange={setStyle} 
            cinematicReference={cinematicReference} 
            onCinematicReferenceChange={setCinematicReference} 
          />
          
          <DurationSelector value={duration} onChange={setDuration} />
          
          <AspectRatioSelector value={aspectRatio} onChange={setAspectRatio} />
        </div>
      </div>

      {/* Action Button */}
      <div className="flex justify-end">
        <button
          onClick={handleGenerate}
          disabled={createFromDoc.isPending || !file}
          className={cn(
            "group relative overflow-hidden flex items-center gap-3 px-8 py-4 rounded-2xl font-bold text-[var(--color-text-inverted)] shadow-none transition-all",
            "bg-[var(--color-bg-inverted)] hover:scale-[1.02]",
            "disabled:opacity-50 disabled:hover:scale-100 disabled:cursor-not-allowed"
          )}
        >
          {createFromDoc.isPending ? (
            <>
              <Loader2 size={20} className="animate-spin" />
              <span>Yapay Zeka Belgeyi Okuyor...</span>
            </>
          ) : (
            <>
              <Wand2 size={20} className="group-hover:rotate-12 transition-transform" />
              <span>Belgeden Video Üret</span>
              <ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
            </>
          )}
        </button>
      </div>

      {/* Info Box */}
      <div className="card p-5 bg-[var(--color-bg-surface)]">
        <div className="flex items-start gap-3">
          <Sparkles size={20} className="text-[var(--color-text-secondary)] shrink-0 mt-0.5" />
          <div className="space-y-2">
            <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
              Nasıl Çalışır?
            </h3>
            <ol className="text-xs text-[var(--color-text-muted)] space-y-1.5 list-decimal list-inside">
              <li>PDF, Word veya TXT formatında bir metin dosyası yükleyin</li>
              <li>MarkItDown AI teknolojisiyle belgeniz analiz edilip özetlenir</li>
              <li>Belgenin içeriğine en uygun görseller ve anlatım senaryosu çıkarılır</li>
              <li>Sizin seçtiğiniz dil, stil ve süreye göre yepyeni bir video oluşturulur</li>
            </ol>
          </div>
        </div>
      </div>
    </div>
  );
}
