'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Loader2, TrendingUp, ChevronRight } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { sessionService, videoService } from '@/services/api';
import { SessionContext } from '@/types';
import { storeVideoFile } from '@/lib/video-storage';
import { ProjectSelectionSection } from '@/components/project-selection-section';
import { Reveal } from '@/components/ui/reveal';
import { cn } from '@/lib/utils';

const DETECTION_METHODS = [
  { value: 'yolo', label: 'Road Defect Detection' },
  // { value: 'yolo_vl', label: 'YOLO with Vision-Language Model' },
  // { value: 'sam3', label: 'OpenAI SAM 3 Segmentation Model' },
  { value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' },
  { value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' },
  { value: 'culvert_detection', label: 'Culvert Detection' },
  { value: 'combined', label: 'Road Defect Detection with vl' },
  // { value: 'gemini_video', label: 'Gemini AI Analysis' },
] as const;

export default function UploadPage() {
  const router = useRouter();
  const [session, setSession] = useState<SessionContext | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // Form states
  const [file, setFile] = useState<File | null>(null);
  const [jsonFile, setJsonFile] = useState<File | null>(null);
  const [selectMethod, setSelectMethod] = useState('yolo');

  // Upload states
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load session on mount
  useEffect(() => {
    // We don't load session on mount for the upload page to ensure
    // project details are filled manually as requested.
    setIsLoading(false);
  }, []);

  const handleSelectionChange = useCallback(
    (selectedSession: SessionContext | null) => {
      setSession(selectedSession);
      if (selectedSession) {
        sessionService.saveSession(selectedSession);
      }
    },
    [],
  );

  const handleUpload = async () => {
    if (!file) {
      setError('Please select a video file');
      return;
    }

    if (!jsonFile) {
      setError('Please select a GPS JSON file');
      return;
    }

    if (!session) {
      setError('Please complete the project selection first');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);
    formData.append('detection_mode', selectMethod);
    formData.append('chainage_id', session.chainageId as string);
    formData.append('json_file', jsonFile);

    setUploading(true);
    setError(null);

    try {
      const result = await videoService.uploadVideo(formData);

      // Store file locally
      if (file) {
        try {
          await storeVideoFile(result.video_id, file);
        } catch (err) {
          console.error('Failed to store video file:', err);
        }
      }

      sessionService.saveVideoData({ videoId: result.video_id });
      router.push(`/upload/${result.video_id}`);
    } catch (err) {
      let errorMessage = 'Upload failed';
      if (err instanceof TypeError && err.message === 'Failed to fetch') {
        errorMessage =
          'Cannot connect to server. Please check if backend is running.';
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      setError(errorMessage);
      setUploading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-10 w-10 animate-spin text-primary" />
      </div>
    );
  }

  const isSessionComplete = !!(
    session && sessionService.isSessionValid(session)
  );
  const isFormValid = isSessionComplete && file && jsonFile;

  return (
    <div className="min-h-screen pb-12">
      <main>
        {/* Header */}
        <div className="mb-10">
          <PageHeader
            title="Intelligent Road Asset AI Analysis"
            description="High-precision detection for potholes, signboards, and culverts from video data"
            icon={TrendingUp}
          />
        </div>

        <div className="space-y-8 mt-8">
          {/* Module 1: Project Selection */}
          <Reveal direction="up" delay={0.1}>
            <Card className="border">
              <CardHeader>
                <CardTitle className="text-xl font-bold">
                  1. Project Details
                </CardTitle>
                <CardDescription>
                  Select the target project, package, and segment.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <ProjectSelectionSection
                  onSelectionChange={handleSelectionChange}
                  asStep={true}
                  hideButton={true}
                />
              </CardContent>
            </Card>
          </Reveal>

          {/* Module 2: Upload Data */}
          <Reveal direction="up" delay={0.2}>
            <Card
              className={cn(
                'border transition-all duration-300',
                !isSessionComplete &&
                  'opacity-60 pointer-events-none grayscale-[0.5]',
              )}
            >
              <CardHeader>
                <CardTitle className="text-xl font-bold flex items-center gap-2">
                  2. Upload Video Data
                </CardTitle>
                <CardDescription>
                  Provide the video file and GPS telemetry for processing.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 gap-6 text-sm">
                  {/* Video File Input */}
                  <div className="space-y-2">
                    <Label
                      htmlFor="video-file"
                      className="text-sm font-semibold"
                    >
                      Video File <span className="text-destructive">*</span>
                    </Label>
                    <div className="relative group">
                      <Input
                        id="video-file"
                        type="file"
                        accept="video/*"
                        onChange={(e) => {
                          setFile(e.target.files?.[0] || null);
                          setError(null);
                        }}
                        disabled={uploading || !isSessionComplete}
                        className="h-12 bg-muted/30 border-dashed border-2 group-hover:border-primary/50 transition-colors cursor-pointer file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary file:text-primary-foreground file:font-semibold file:text-xs"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* JSON File Input */}
                    <div className="space-y-2">
                      <Label
                        htmlFor="json-file"
                        className="text-sm font-semibold"
                      >
                        GPS JSON File{' '}
                        <span className="text-destructive">*</span>
                      </Label>
                      <Input
                        id="json-file"
                        type="file"
                        accept=".json,application/json"
                        onChange={(e) => {
                          setJsonFile(e.target.files?.[0] || null);
                          setError(null);
                        }}
                        disabled={uploading || !isSessionComplete}
                        required
                        className="h-11 bg-muted/30 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs"
                      />
                    </div>

                    {/* Select Method */}
                    <div className="space-y-2">
                      <Label
                        htmlFor="select-method"
                        className="text-sm font-semibold"
                      >
                        Analysis Method
                      </Label>
                      <Select
                        value={selectMethod}
                        onValueChange={setSelectMethod}
                        disabled={uploading || !isSessionComplete}
                      >
                        <SelectTrigger
                          id="select-method"
                          className="h-11 bg-muted/20"
                        >
                          <SelectValue placeholder="Select method" />
                        </SelectTrigger>
                        <SelectContent>
                          {DETECTION_METHODS.map((method) => (
                            <SelectItem key={method.value} value={method.value}>
                              {method.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

                {/* Error Display */}
                {error && (
                  <div className="p-4 rounded-md bg-destructive/5 border border-destructive/20 text-destructive text-sm font-medium animate-in fade-in slide-in-from-top-1">
                    {error}
                  </div>
                )}

                {/* Primary Action Button */}
                <div className="pt-2">
                  <Button
                    onClick={handleUpload}
                    disabled={!isFormValid || uploading}
                    className="w-full h-14 font-extrabold uppercase tracking-wider"
                  >
                    {uploading ? (
                      <div className="flex items-center gap-3">
                        <Loader2 className="h-5 w-5 animate-spin" />
                        <span>Uploading...</span>
                      </div>
                    ) : (
                      <div className="flex items-center gap-2">
                        <span>Upload & Process Analysis</span>
                        <ChevronRight className="h-5 w-5" />
                      </div>
                    )}
                  </Button>
                </div>
              </CardContent>
            </Card>
          </Reveal>
        </div>
      </main>
    </div>
  );
}
