'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
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 { useToast } from '@/hooks/use-toast';
import { createImport, getLayoutConfigurations } from '@/app/actions/imports';
import { uploadFile } from '@/app/actions/file-upload';

interface LayoutConfiguration {
  id: number;
  name: string;
}

interface CreateImportDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess?: () => void;
}

export function CreateImportDialog({ open, onOpenChange, onSuccess }: CreateImportDialogProps) {
  const [name, setName] = useState('');
  const [layoutId, setLayoutId] = useState<string>('');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [layouts, setLayouts] = useState<LayoutConfiguration[]>([]);
  const [loadingLayouts, setLoadingLayouts] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    async function loadLayouts() {
      try {
        const result = await getLayoutConfigurations();
        if (result.success && result.data) {
          setLayouts(result.data);
        }
      } catch {
        toast({
          title: 'Error',
          description: 'Failed to load layout configurations',
          variant: 'destructive',
        });
      } finally {
        setLoadingLayouts(false);
      }
    }

    if (open) {
      loadLayouts();
    }
  }, [open, toast]);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      // Auto-fill name from filename if empty
      if (!name.trim()) {
        setName(file.name.replace(/\.[^/.]+$/, ''));
      }
    }
  };

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    if (!selectedFile) {
      toast({
        title: 'Error',
        description: 'Please select a file to upload',
        variant: 'destructive',
      });
      return;
    }

    if (!name.trim()) {
      toast({
        title: 'Error',
        description: 'Please enter an import name',
        variant: 'destructive',
      });
      return;
    }

    if (!layoutId) {
      toast({
        title: 'Error',
        description: 'Please select a layout configuration',
        variant: 'destructive',
      });
      return;
    }

    setLoading(true);

    try {
      // First, upload the file
      const uploadResult = await uploadFile(selectedFile);
      if (!uploadResult.success) {
        toast({
          title: 'Error',
          description: uploadResult.error || 'Failed to upload file',
          variant: 'destructive',
        });
        return;
      }

      // Then create the import with the file reference
      const result = await createImport({
        name: name.trim(),
        layoutId: parseInt(layoutId),
        fileId: uploadResult.data?.id,
      });

      if (result.success) {
        toast({
          title: 'Success',
          description: 'Import created successfully',
        });
        setName('');
        setLayoutId('');
        setSelectedFile(null);
        onOpenChange(false);
        onSuccess?.();
      } else {
        toast({
          title: 'Error',
          description: result.error || 'Failed to create import',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Failed to create import',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Create New Import</DialogTitle>
          <DialogDescription>
            Upload a file and create a new import with a layout configuration.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="file">Upload File</Label>
              <Input
                id="file"
                type="file"
                onChange={handleFileChange}
                accept=".csv,.xlsx,.xls"
                disabled={loading}
              />
              {selectedFile && (
                <p className="text-sm text-muted-foreground">
                  Selected: {selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
                </p>
              )}
            </div>
            <div className="grid gap-2">
              <Label htmlFor="name">Import Name</Label>
              <Input
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Enter import name"
                disabled={loading}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="layout">Layout Configuration</Label>
              <Select value={layoutId} onValueChange={setLayoutId} disabled={loadingLayouts || loading}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a layout configuration" />
                </SelectTrigger>
                <SelectContent>
                  {layouts.map((layout) => (
                    <SelectItem key={layout.id} value={layout.id.toString()}>
                      {layout.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
              Cancel
            </Button>
            <Button 
              type="submit" 
              disabled={loading || !selectedFile || !name || !layoutId}
            >
              {loading ? 'Creating...' : 'Create Import'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}