import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { toast } from '@/hooks/use-toast';
import { useIsMobile } from '@/hooks/use-mobile';
import { useUserRole } from '@/hooks/useUserRole';
import { useAuth } from '@/hooks/useAuth';
import { editSubmissionItem, type SubmissionItemWithDeps } from '@/lib/submissionItemsService';
import { ParkForm } from '@/components/admin/ParkForm';
import { RideForm } from '@/components/admin/RideForm';
import { ManufacturerForm } from '@/components/admin/ManufacturerForm';
import { DesignerForm } from '@/components/admin/DesignerForm';
import { OperatorForm } from '@/components/admin/OperatorForm';
import { PropertyOwnerForm } from '@/components/admin/PropertyOwnerForm';
import { RideModelForm } from '@/components/admin/RideModelForm';
import { Save, X, Edit } from 'lucide-react';

interface ItemEditDialogProps {
  item: SubmissionItemWithDeps | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onComplete: () => void;
}

export function ItemEditDialog({ item, open, onOpenChange, onComplete }: ItemEditDialogProps) {
  const [submitting, setSubmitting] = useState(false);
  const isMobile = useIsMobile();
  const { isModerator } = useUserRole();
  const { user } = useAuth();
  const Container = isMobile ? Sheet : Dialog;

  if (!item) return null;

  const handleSubmit = async (data: any) => {
    if (!user?.id) {
      toast({
        title: 'Authentication Required',
        description: 'You must be logged in to edit items',
        variant: 'destructive',
      });
      return;
    }

    setSubmitting(true);
    try {
      await editSubmissionItem(item.id, data, user.id);
      
      toast({
        title: isModerator() ? 'Item Updated' : 'Edit Submitted',
        description: isModerator() 
          ? 'The item has been updated successfully.'
          : 'Your edit has been submitted and will be reviewed by a moderator.',
      });

      onComplete();
      onOpenChange(false);
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message || 'Failed to save changes',
        variant: 'destructive',
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handlePhotoSubmit = async (caption: string, credit: string) => {
    const photoData = {
      ...item.item_data,
      photos: item.item_data.photos?.map((photo: any) => ({
        ...photo,
        caption,
        credit,
      })),
    };
    await handleSubmit(photoData);
  };

  const renderEditForm = () => {
    const data = item.item_data;

    switch (item.item_type) {
      case 'park':
        return (
          <ParkForm
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
            isEditing
          />
        );

      case 'ride':
        return (
          <RideForm
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
            isEditing
          />
        );

      case 'manufacturer':
        return (
          <ManufacturerForm
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
          />
        );

      case 'designer':
        return (
          <DesignerForm
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
          />
        );

      case 'operator':
        return (
          <OperatorForm
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
          />
        );

      case 'property_owner':
        return (
          <PropertyOwnerForm
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
          />
        );

      case 'ride_model':
        return (
          <RideModelForm
            manufacturerName={data.manufacturer_name || 'Unknown'}
            manufacturerId={data.manufacturer_id}
            onSubmit={handleSubmit}
            onCancel={() => onOpenChange(false)}
            initialData={data}
          />
        );

      case 'photo':
        return (
          <PhotoEditForm
            photos={data.photos || []}
            onSubmit={handlePhotoSubmit}
            onCancel={() => onOpenChange(false)}
            submitting={submitting}
          />
        );

      default:
        return (
          <div className="text-center py-8 text-muted-foreground">
            No edit form available for this item type
          </div>
        );
    }
  };

  return (
    <Container open={open} onOpenChange={onOpenChange}>
      {isMobile ? (
        <SheetContent side="bottom" className="h-[90vh] overflow-y-auto">
          <SheetHeader>
            <SheetTitle className="flex items-center gap-2">
              <Edit className="w-5 h-5" />
              Edit {item.item_type.replace('_', ' ')}
            </SheetTitle>
            <SheetDescription>
              Make changes to this submission item
            </SheetDescription>
          </SheetHeader>
          <div className="mt-6">
            {renderEditForm()}
          </div>
        </SheetContent>
      ) : (
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="w-5 h-5" />
              Edit {item.item_type.replace('_', ' ')}
            </DialogTitle>
            <DialogDescription>
              Make changes to this submission item
            </DialogDescription>
          </DialogHeader>
          <div className="mt-4">
            {renderEditForm()}
          </div>
        </DialogContent>
      )}
    </Container>
  );
}

// Simple photo editing form for caption and credit
function PhotoEditForm({ 
  photos, 
  onSubmit, 
  onCancel, 
  submitting 
}: { 
  photos: any[]; 
  onSubmit: (caption: string, credit: string) => void; 
  onCancel: () => void;
  submitting: boolean;
}) {
  const [caption, setCaption] = useState(photos[0]?.caption || '');
  const [credit, setCredit] = useState(photos[0]?.credit || '');

  return (
    <div className="space-y-6">
      {/* Photo Preview */}
      <div className="grid grid-cols-3 gap-2">
        {photos.slice(0, 3).map((photo, idx) => (
          <img
            key={idx}
            src={photo.url}
            alt={photo.caption || 'Photo'}
            className="w-full h-32 object-cover rounded"
          />
        ))}
      </div>

      {/* Caption */}
      <div className="space-y-2">
        <Label htmlFor="caption">Caption</Label>
        <Textarea
          id="caption"
          value={caption}
          onChange={(e) => setCaption(e.target.value)}
          placeholder="Describe the photo..."
          rows={3}
        />
      </div>

      {/* Credit */}
      <div className="space-y-2">
        <Label htmlFor="credit">Photo Credit</Label>
        <Input
          id="credit"
          value={credit}
          onChange={(e) => setCredit(e.target.value)}
          placeholder="Photographer name"
        />
      </div>

      {/* Actions */}
      <div className="flex gap-3 justify-end">
        <Button type="button" variant="outline" onClick={onCancel} disabled={submitting}>
          <X className="w-4 h-4 mr-2" />
          Cancel
        </Button>
        <Button onClick={() => onSubmit(caption, credit)} disabled={submitting}>
          <Save className="w-4 h-4 mr-2" />
          {submitting ? 'Saving...' : 'Save Changes'}
        </Button>
      </div>
    </div>
  );
}
