import React, { useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Box,
  Tabs,
  Tab,
  Typography,
  Switch,
  FormControlLabel,
  Grid,
  Autocomplete,
} from '@mui/material';
import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { 
  Package, 
  CreatePackageRequest,
  Build 
} from '../../types';
import { useProjects, useProjectBuilds } from '../../hooks/useProjects';
import { useCreatePackage, useUpdatePackage } from '../../hooks/usePackages';
import { LoadingSpinner } from '../common/LoadingSpinner';

interface PackageFormProps {
  open: boolean;
  onClose: () => void;
  package?: Package;
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel: React.FC<TabPanelProps> = ({ children, value, index, ...other }) => (
  <div
    role="tabpanel"
    hidden={value !== index}
    id={`package-tabpanel-${index}`}
    aria-labelledby={`package-tab-${index}`}
    {...other}
  >
    {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
  </div>
);

const schema = yup.object({
  title: yup.string().required('Title is required'),
  version: yup.string().required('Version is required'),
  description: yup.string().required('Description is required'),
  projectId: yup.number().required('Project is required'),
  sourceBuildId: yup.number().required('Source build is required'),
  configuration: yup.object({
    buildFolder: yup.string().required('Build folder is required'),
    zipContents: yup.boolean().required(),
    deleteOldPublishedBuilds: yup.boolean().required(),
    releaseNoteTemplate: yup.string().required('Release note template is required'),
    storageSettings: yup.object().required(),
    helpCenterSettings: yup.object().required(),
  }),
});

export const PackageForm: React.FC<PackageFormProps> = ({ open, onClose, package: pkg }) => {
  const [currentTab, setCurrentTab] = React.useState(0);
  const [selectedProjectId, setSelectedProjectId] = React.useState<number | null>(null);
  
  const { data: projectsData } = useProjects();
  const { data: buildsData } = useProjectBuilds(
    selectedProjectId || 0,
    1,
    50,
    { status: 'Success' }
  );
  
  const createMutation = useCreatePackage();
  const updateMutation = useUpdatePackage();
  
  const {
    control,
    handleSubmit,
    reset,
    watch,
    formState: { errors, isValid },
  } = useForm<CreatePackageRequest>({
    resolver: yupResolver(schema),
    defaultValues: {
      title: '',
      version: '',
      description: '',
      projectId: 0,
      sourceBuildId: 0,
      configuration: {
        buildFolder: '',
        zipContents: true,
        deleteOldPublishedBuilds: true,
        releaseNoteTemplate: '',
        storageSettings: {},
        helpCenterSettings: {},
      },
    },
  });

  const watchedProjectId = watch('projectId');

  useEffect(() => {
    if (watchedProjectId) {
      setSelectedProjectId(watchedProjectId);
    }
  }, [watchedProjectId]);

  useEffect(() => {
    if (pkg) {
      reset({
        title: pkg.title,
        version: pkg.version,
        description: pkg.description,
        projectId: pkg.projectId,
        sourceBuildId: pkg.sourceBuildId,
        configuration: pkg.configuration || {
          buildFolder: '',
          zipContents: true,
          deleteOldPublishedBuilds: true,
          releaseNoteTemplate: '',
          storageSettings: {},
          helpCenterSettings: {},
        },
      });
      setSelectedProjectId(pkg.projectId);
    } else {
      reset({
        title: '',
        version: '',
        description: '',
        projectId: 0,
        sourceBuildId: 0,
        configuration: {
          buildFolder: '',
          zipContents: true,
          deleteOldPublishedBuilds: true,
          releaseNoteTemplate: '',
          storageSettings: {},
          helpCenterSettings: {},
        },
      });
      setSelectedProjectId(null);
    }
  }, [pkg, reset]);

  const onSubmit = async (data: CreatePackageRequest) => {
    try {
      if (pkg) {
        await updateMutation.mutateAsync({ id: pkg.id, request: data });
      } else {
        await createMutation.mutateAsync(data);
      }
      onClose();
    } catch (error) {
      console.error('Failed to save package:', error);
    }
  };

  const handleClose = () => {
    setCurrentTab(0);
    onClose();
  };

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

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <form onSubmit={handleSubmit(onSubmit)}>
        <DialogTitle>
          {pkg ? 'Edit Package' : 'Create Package'}
        </DialogTitle>
        
        <DialogContent>
          <Tabs value={currentTab} onChange={(_, newValue) => setCurrentTab(newValue)}>
            <Tab label="Basic Info" />
            <Tab label="Configuration" />
            <Tab label="Storage" />
            <Tab label="Help Center" />
          </Tabs>

          {/* Basic Info Tab */}
          <TabPanel value={currentTab} index={0}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="title"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Title"
                      fullWidth
                      error={!!errors.title}
                      helperText={errors.title?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="version"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Version"
                      fullWidth
                      error={!!errors.version}
                      helperText={errors.version?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Description"
                      fullWidth
                      multiline
                      rows={3}
                      error={!!errors.description}
                      helperText={errors.description?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="projectId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth error={!!errors.projectId}>
                      <InputLabel>Project</InputLabel>
                      <Select
                        {...field}
                        label="Project"
                      >
                        {projects.map((project) => (
                          <MenuItem key={project.id} value={project.id}>
                            {project.name}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="sourceBuildId"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      options={builds}
                      getOptionLabel={(build: Build) => 
                        `${build.buildNumber} (${new Date(build.endTime).toLocaleDateString()})`
                      }
                      value={builds.find(b => b.id === field.value) || null}
                      onChange={(_, value) => field.onChange(value?.id || 0)}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Source Build"
                          error={!!errors.sourceBuildId}
                          helperText={errors.sourceBuildId?.message}
                        />
                      )}
                      disabled={!selectedProjectId}
                    />
                  )}
                />
              </Grid>
            </Grid>
          </TabPanel>

          {/* Configuration Tab */}
          <TabPanel value={currentTab} index={1}>
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <Controller
                  name="configuration.buildFolder"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Build Folder Path"
                      fullWidth
                      error={!!errors.configuration?.buildFolder}
                      helperText={errors.configuration?.buildFolder?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="configuration.zipContents"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="ZIP Contents"
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="configuration.deleteOldPublishedBuilds"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="Delete Old Published Builds"
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="configuration.releaseNoteTemplate"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Release Note Template"
                      fullWidth
                      multiline
                      rows={4}
                      error={!!errors.configuration?.releaseNoteTemplate}
                      helperText={errors.configuration?.releaseNoteTemplate?.message}
                      placeholder="Template variables: {{VERSION}}, {{DATE}}, {{PROJECT}}"
                    />
                  )}
                />
              </Grid>
            </Grid>
          </TabPanel>

          {/* Storage Tab */}
          <TabPanel value={currentTab} index={2}>
            <Typography variant="h6" gutterBottom>
              Storage Configuration
            </Typography>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Configure cloud storage settings for package deployment.
            </Typography>
            {/* Storage configuration fields would go here */}
            <TextField
              label="Storage Provider"
              fullWidth
              margin="normal"
              placeholder="AWS S3, Box.com, FTP"
            />
          </TabPanel>

          {/* Help Center Tab */}
          <TabPanel value={currentTab} index={3}>
            <Typography variant="h6" gutterBottom>
              Help Center Configuration
            </Typography>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Configure automatic help center article updates.
            </Typography>
            {/* Help center configuration fields would go here */}
            <TextField
              label="Article ID"
              fullWidth
              margin="normal"
            />
          </TabPanel>
        </DialogContent>

        <DialogActions>
          <Button onClick={handleClose}>Cancel</Button>
          <Button
            type="submit"
            variant="contained"
            disabled={!isValid || createMutation.isPending || updateMutation.isPending}
          >
            {createMutation.isPending || updateMutation.isPending ? (
              <LoadingSpinner size={20} />
            ) : pkg ? (
              'Update'
            ) : (
              'Create'
            )}
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
};