'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';

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 [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]);

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

    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 {
      const result = await createImport({
        name: name.trim(),
        layoutId: parseInt(layoutId),
      });

      if (result.success) {
        toast({
          title: 'Success',
          description: 'Import created successfully',
        });
        setName('');
        setLayoutId('');
        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-[425px]">
        <DialogHeader>
          <DialogTitle>Create New Import</DialogTitle>
          <DialogDescription>
            Create a new import with a layout configuration and file name.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="grid gap-4 py-4">
            <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 || !name || !layoutId}>
              {loading ? 'Creating...' : 'Create Import'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}