'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, FileText, Calendar, Trash2, Edit } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { format } from 'date-fns';
import { getImports, deleteImport } from '@/app/actions/imports';
import { CreateImportDialog } from '@/app/components/imports/CreateImportDialog';
import { EditImportDialog } from '@/app/components/imports/EditImportDialog';
import { ImportDetailDialog } from '@/app/components/imports/ImportDetailDialog';
import { useToast } from '@/hooks/use-toast';

interface Import {
  id: number;
  name: string;
  importDate: string;
  layoutId: number;
  layout: {
    id: number;
    name: string;
  };
}

interface RawImportData {
  id: number;
  name: string;
  importDate: Date | string;
  layoutId: number;
  layout: {
    id: number;
    name: string;
  };
}

export default function ImportsPage() {
  const [imports, setImports] = useState<Import[]>([]);
  const [loading, setLoading] = useState(true);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedImport, setSelectedImport] = useState<Import | null>(null);
  const { toast } = useToast();

  const loadImports = useCallback(async () => {
    try {
      const result = await getImports();
      if (result.success && result.data) {
        // Transform the data to match our Import interface
        const transformedImports = result.data.map((item: RawImportData) => ({
          id: item.id,
          name: item.name,
          importDate: item.importDate instanceof Date
            ? item.importDate.toISOString()
            : String(item.importDate),
          layoutId: item.layoutId,
          layout: {
            id: item.layout.id,
            name: item.layout.name,
          },
        }));
        setImports(transformedImports);
      } else {
        toast({
          title: 'Error',
          description: result.error || 'Failed to load imports',
          variant: 'destructive',
        });
        setImports([]);
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Failed to load imports',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadImports();
  }, [loadImports]);

  async function handleDeleteImport(id: number) {
    if (!confirm('Are you sure you want to delete this import?')) return;

    try {
      const result = await deleteImport(id);
      if (result.success) {
        toast({
          title: 'Success',
          description: 'Import deleted successfully',
        });
        loadImports();
      } else {
        toast({
          title: 'Error',
          description: result.error || 'Failed to delete import',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Failed to delete import',
        variant: 'destructive',
      });
    }
  }

  function handleEditImport(importRecord: Import) {
    setSelectedImport(importRecord);
    setEditDialogOpen(true);
  }

  function handleViewImport(importRecord: Import) {
    setSelectedImport(importRecord);
    setDetailDialogOpen(true);
  }

  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <div className="flex justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-3xl font-bold">Import Management</h1>
          <p className="text-muted-foreground">Manage your data imports and configurations</p>
        </div>
        <Button onClick={() => setCreateDialogOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          Create Import
        </Button>
      </div>

      {imports.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <FileText className="h-12 w-12 text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold mb-2">No imports yet</h3>
            <p className="text-muted-foreground mb-4">
              Get started by creating your first import
            </p>
            <Button onClick={() => setCreateDialogOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Create Import
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {imports.map((importRecord) => (
            <Card key={importRecord.id} className="hover:shadow-lg transition-shadow">
              <CardHeader>
                <div className="flex justify-between items-start">
                  <div>
                    <CardTitle className="text-lg">{importRecord.name}</CardTitle>
                    <CardDescription>
                      Layout: {importRecord.layout.name}
                    </CardDescription>
                  </div>
                  <Badge variant="outline">
                    <Calendar className="mr-1 h-3 w-3" />
                    {format(new Date(importRecord.importDate), 'MMM d, yyyy')}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex justify-between items-center">
                  <div className="flex gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewImport(importRecord)}
                    >
                      <FileText className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEditImport(importRecord)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDeleteImport(importRecord.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <CreateImportDialog
        open={createDialogOpen}
        onOpenChange={setCreateDialogOpen}
        onSuccess={loadImports}
      />

      <EditImportDialog
        open={editDialogOpen}
        onOpenChange={setEditDialogOpen}
        importRecord={selectedImport}
        onSuccess={loadImports}
      />

      <ImportDetailDialog
        open={detailDialogOpen}
        onOpenChange={setDetailDialogOpen}
        importId={selectedImport?.id || 0}
      />
    </div>
  );
}