'use client';

import { useState, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useCameraStore } from '@/stores/camera-store';
import { useTranslation } from '@/lib/i18n';
import { cn } from '@/lib/utils';

interface SourceSelectorProps {
  deviceId: string;
}

export function SourceSelector({ deviceId }: SourceSelectorProps) {
  const { t } = useTranslation();
  const {
    cameras,
    isStreaming,
    sourceType,
    sourceFilename,
    isUploading,
    startPipeline,
    stopPipeline,
    uploadImage,
    uploadVideo,
    uploadBatchImages,
    startFromUrl,
  } = useCameraStore();

  const [mounted, setMounted] = useState(false);
  const hasCameras = cameras.length > 0;
  const [cameraDisabled, setCameraDisabled] = useState(false);
  const [activeTab, setActiveTab] = useState<'camera' | 'image' | 'video'>('camera');

  useEffect(() => {
    setMounted(true);
  }, []);

  // After mount, check if cameras are available and switch tab if needed
  useEffect(() => {
    if (!hasCameras) {
      setCameraDisabled(true);
      if (activeTab === 'camera') {
        setActiveTab('image');
      }
    } else {
      setCameraDisabled(false);
    }
  }, [hasCameras, activeTab]);
  const [videoMode, setVideoMode] = useState<'file' | 'url'>('file');
  const [videoUrl, setVideoUrl] = useState('');
  const [isDragging, setIsDragging] = useState(false);
  const imageFileRef = useRef<HTMLInputElement>(null);
  const videoFileRef = useRef<HTMLInputElement>(null);

  const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;
    if (files.length === 1) {
      await uploadImage(files[0], deviceId);
    } else {
      await uploadBatchImages(files, deviceId);
    }
    if (imageFileRef.current) imageFileRef.current.value = '';
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };
  const handleDragLeave = () => setIsDragging(false);
  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const files = Array.from(e.dataTransfer.files).filter((f) =>
      ['.jpg', '.jpeg', '.png'].some((ext) => f.name.toLowerCase().endsWith(ext))
    );
    if (files.length === 0) return;
    if (files.length === 1) {
      await uploadImage(files[0], deviceId);
    } else {
      await uploadBatchImages(files, deviceId);
    }
  };

  const handleVideoSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    await uploadVideo(file, deviceId);
    if (videoFileRef.current) videoFileRef.current.value = '';
  };

  const handleUrlSubmit = async () => {
    if (!videoUrl.trim()) return;
    await startFromUrl(videoUrl.trim(), deviceId);
    setVideoUrl('');
  };

  const sourceLabel =
    sourceType === 'camera' ? t('camera.camera') : sourceType === 'image' ? t('camera.image') : sourceType === 'batch_image' ? t('camera.batchImages') : t('camera.video');

  if (!mounted) return null;

  return (
    <div className="space-y-3">
      <Tabs
        value={activeTab}
        onValueChange={(v) => setActiveTab(v as typeof activeTab)}
      >
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="camera" disabled={isStreaming || cameraDisabled}>
            {t('camera.camera')}
          </TabsTrigger>
          <TabsTrigger value="image" disabled={isStreaming}>
            {t('camera.image')}
          </TabsTrigger>
          <TabsTrigger value="video" disabled={isStreaming}>
            {t('camera.video')}
          </TabsTrigger>
        </TabsList>
      </Tabs>

      <div className="flex items-center gap-3">
        {isStreaming ? (
          <>
            <Button variant="destructive" onClick={stopPipeline}>
              {sourceType === 'camera' ? t('camera.stopCamera') : sourceType === 'image' ? t('camera.stopImage') : sourceType === 'batch_image' ? t('camera.stopBatch') : t('camera.stopVideo')}
            </Button>
            {sourceFilename && (
              <span className="text-sm text-muted-foreground truncate max-w-48">
                {sourceFilename}
              </span>
            )}
          </>
        ) : (
          <>
            {activeTab === 'camera' && (
              hasCameras ? (
                <Button onClick={() => startPipeline(cameras[0]?.id ?? '', deviceId)}>
                  {t('camera.startCamera')}
                </Button>
              ) : (
                <p className="text-sm text-muted-foreground">
                  {t('camera.noCameraDetected')}
                </p>
              )
            )}

            {activeTab === 'image' && (
              <div
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                className={cn(
                  'flex-1 rounded-lg border-2 border-dashed p-3 transition-colors',
                  isDragging ? 'border-primary bg-primary/5' : 'border-transparent'
                )}
              >
                <div className="flex items-center gap-3">
                  <Button
                    onClick={() => imageFileRef.current?.click()}
                    disabled={isUploading}
                  >
                    {isUploading ? t('common.uploading') : t('camera.selectImages')}
                  </Button>
                  <span className="text-sm text-muted-foreground">
                    {t('camera.jpgPngMultiple')}
                  </span>
                </div>
                {isDragging && (
                  <p className="mt-2 text-sm text-primary">{t('camera.dropImagesHere')}</p>
                )}
                <input
                  ref={imageFileRef}
                  type="file"
                  accept=".jpg,.jpeg,.png"
                  multiple
                  className="hidden"
                  onChange={handleImageSelect}
                />
              </div>
            )}

            {activeTab === 'video' && (
              <div className="flex flex-col gap-2 w-full">
                <div className="flex items-center gap-2">
                  <Button
                    variant={videoMode === 'file' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => setVideoMode('file')}
                  >
                    {t('camera.uploadFile')}
                  </Button>
                  <Button
                    variant={videoMode === 'url' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => setVideoMode('url')}
                  >
                    {t('camera.pasteUrl')}
                  </Button>
                </div>

                {videoMode === 'file' ? (
                  <div className="flex items-center gap-3">
                    <Button
                      onClick={() => videoFileRef.current?.click()}
                      disabled={isUploading}
                    >
                      {isUploading ? t('common.uploading') : t('camera.selectVideo')}
                    </Button>
                    <span className="text-sm text-muted-foreground">
                      {t('camera.mp4AviMov')}
                    </span>
                    <input
                      ref={videoFileRef}
                      type="file"
                      accept=".mp4,.avi,.mov"
                      className="hidden"
                      onChange={handleVideoSelect}
                    />
                  </div>
                ) : (
                  <div className="flex flex-col gap-1.5">
                    <div className="flex items-center gap-2">
                      <Input
                        placeholder={t('camera.urlPlaceholder')}
                        value={videoUrl}
                        onChange={(e) => setVideoUrl(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') handleUrlSubmit();
                        }}
                        className="flex-1"
                      />
                      <Button
                        onClick={handleUrlSubmit}
                        disabled={isUploading || !videoUrl.trim()}
                      >
                        {isUploading ? t('common.loading') : t('common.start')}
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('camera.urlHelpText')}
                    </p>
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
