import React, { useState } from 'react';
import { 
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from '@mui/material';
import { PackageList } from '../components/Packages/PackageList';
import { PackageForm } from '../components/Packages/PackageForm';
import { usePublishPackage } from '../hooks/usePackages';
import { useProjectBuilds } from '../hooks/useProjects';
import { Package, Build } from '../types';

export const PackagesPage: React.FC = () => {
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingPackage, setEditingPackage] = useState<Package | null>(null);
  const [publishingPackage, setPublishingPackage] = useState<Package | null>(null);
  const [selectedBuildId, setSelectedBuildId] = useState<number>(0);

  const publishMutation = usePublishPackage();
  const { data: buildsData } = useProjectBuilds(
    publishingPackage?.projectId || 0,
    1,
    50,
    { status: 'Success' }
  );

  const handleCreatePackage = () => {
    setShowCreateForm(true);
  };

  const handleEditPackage = (packageItem: Package) => {
    setEditingPackage(packageItem);
  };

  const handlePublishPackage = (packageItem: Package) => {
    setPublishingPackage(packageItem);
    setSelectedBuildId(packageItem.sourceBuildId);
  };

  const handleCloseCreateForm = () => {
    setShowCreateForm(false);
  };

  const handleCloseEditForm = () => {
    setEditingPackage(null);
  };

  const handleConfirmPublish = async () => {
    if (publishingPackage && selectedBuildId) {
      try {
        await publishMutation.mutateAsync({
          packageId: publishingPackage.id,
          buildId: selectedBuildId,
        });
        setPublishingPackage(null);
        setSelectedBuildId(0);
      } catch (error) {
        console.error('Failed to publish package:', error);
      }
    }
  };

  const handleCancelPublish = () => {
    setPublishingPackage(null);
    setSelectedBuildId(0);
  };

  const builds = buildsData?.data || [];

  return (
    <>
      <PackageList
        onCreatePackage={handleCreatePackage}
        onEditPackage={handleEditPackage}
        onPublishPackage={handlePublishPackage}
      />

      {/* Create Package Form */}
      <PackageForm
        open={showCreateForm}
        onClose={handleCloseCreateForm}
      />

      {/* Edit Package Form */}
      <PackageForm
        open={!!editingPackage}
        onClose={handleCloseEditForm}
        package={editingPackage || undefined}
      />

      {/* Publish Package Dialog */}
      <Dialog
        open={!!publishingPackage}
        onClose={handleCancelPublish}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          Publish Package
        </DialogTitle>
        <DialogContent>
          <Typography variant="body1" gutterBottom>
            Are you sure you want to publish "<strong>{publishingPackage?.title}</strong>"?
          </Typography>
          <Typography variant="body2" color="text.secondary" gutterBottom>
            This will start the publishing workflow and deploy the package to configured storage and help center locations.
          </Typography>
          
          <FormControl fullWidth margin="normal">
            <InputLabel>Source Build</InputLabel>
            <Select
              value={selectedBuildId}
              onChange={(e) => setSelectedBuildId(Number(e.target.value))}
              label="Source Build"
            >
              {builds.map((build: Build) => (
                <MenuItem key={build.id} value={build.id}>
                  {build.buildNumber} ({new Date(build.endTime).toLocaleDateString()})
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelPublish}>
            Cancel
          </Button>
          <Button
            onClick={handleConfirmPublish}
            variant="contained"
            disabled={!selectedBuildId || publishMutation.isPending}
          >
            {publishMutation.isPending ? 'Publishing...' : 'Publish'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};