'use client';

import React, { useState, useEffect } from 'react';
import {
  Typography,
  Grid,
  Box,
  Card,
  Stack,
  alpha,
  useTheme,
} from '@mui/material';

import FormField from '@/shared/components/form/form-field';
import ActionButtons from '@/shared/components/form/buttons-action';
import { Language as LanguageIcon } from '@mui/icons-material';
import { formFields } from '../utils/form-fields-language';

import { ILanguageSettings } from '@/shared/types/ILanguageSettings';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { faGlobe, faCalendarDay, faClock, faHashtag } from '@fortawesome/free-solid-svg-icons';

import { validationSchema } from '../utils/language-settings-validation';
import { INITIAL_LANGUAGE_SETTINGS } from '@/shared/_mock/_langues';
import { useFormik } from 'formik';
import { InfoItem } from '../../styled-component';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';


export default function LanguageSettingsView() {
  const [isEditing, setIsEditing] = useState(false);
  const [currentSettings, setCurrentSettings] = useState<ILanguageSettings>(INITIAL_LANGUAGE_SETTINGS);
  const theme = useTheme();

  useEffect(() => {
    const loadSettings = async () => {
      await new Promise(resolve => setTimeout(resolve, 500));
      setCurrentSettings(INITIAL_LANGUAGE_SETTINGS);
    };
    loadSettings();
  }, []);

  const formik = useFormik<ILanguageSettings>({
    initialValues: currentSettings,
    validationSchema,
    enableReinitialize: true,
    onSubmit: async (values) => {
    }
  });

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleCancel = () => {
    formik.resetForm();
    setIsEditing(false);
  };

  const getOptionLabel = (fieldName: string, value: string): string => {
    const field = formFields.find(f => f.name === fieldName);
    if (field && field.options) {
      const option = field.options.find(opt => opt.value === value);
      if (option) {
        return typeof option.label === 'string' 
          ? option.label 
          : String(option.label);
      }
      return value;
    }
    return value;
  };

  const ViewMode = () => (
    <Grid container spacing={5}>
      <Grid item xs={12} md={6}>
        <Typography variant="h6" sx={{ mb: 3, color: 'text.primary', fontWeight: 'bold' }}>
          Langue et région
        </Typography>
        <Stack spacing={2.5}>
          <InfoItem 
            icon={faGlobe} 
            label="Langue" 
            value={getOptionLabel('language', currentSettings.language)} 
          />
          <InfoItem 
            icon={faGlobe} 
            label="Région" 
            value={getOptionLabel('region', currentSettings.region)} 
          />
        </Stack>
      </Grid>

      <Grid item xs={12} md={6}>
        <Typography variant="h6" sx={{ mb: 3, color: 'text.primary', fontWeight: 'bold' }}>
          Formats d&apos;affichage
        </Typography>
        <Stack spacing={2.5}>
          <InfoItem 
            icon={faCalendarDay} 
            label="Format de date" 
            value={getOptionLabel('dateFormat', currentSettings.dateFormat)} 
          />
          <InfoItem 
            icon={faClock} 
            label="Format d'heure" 
            value={getOptionLabel('timeFormat', currentSettings.timeFormat)} 
          />
          <InfoItem 
            icon={faHashtag} 
            label="Format de nombre" 
            value={getOptionLabel('numberFormat', currentSettings.numberFormat)} 
          />
        </Stack>
      </Grid>
    </Grid>
  );

  const renderEditMode = () => (
    <form onSubmit={formik.handleSubmit}>
      <Grid container spacing={3}>
        {formFields.map((field) => (
          <Grid item xs={12} sm={6} key={field.name}>
            <FormField
              field={field}
              value={formik.values[field.name as keyof ILanguageSettings]}
              onChange={(name, value) => formik.setFieldValue(name, value)}
              error={
                formik.touched[field.name as keyof ILanguageSettings]
                  ? (formik.errors[field.name as keyof ILanguageSettings] as string)
                  : undefined
              }
              onBlur={formik.handleBlur}
              isReadOnly={false}
            />
          </Grid>
        ))}
        <Grid item xs={12}>
          <ActionButtons
            onSave={formik.submitForm}
            onCancel={handleCancel}
            mode="edit"
          />
        </Grid>
      </Grid>
    </form>
  );

  return (
    <Stack spacing={3}>
      <Card sx={{ p: 3, pb: 5 }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 4 }}>
          <Stack direction="row" alignItems="center" spacing={3}>
            <Box
              sx={{
                width: 80,
                height: 80,
                borderRadius: 2,
                border: `2px solid ${theme.palette.primary.main}`,
                bgcolor: alpha(theme.palette.primary.main, 0.15),
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <LanguageIcon sx={{ fontSize: 40, color: 'primary.main' }} />
            </Box>
            <Box>
              <Typography variant="h4" gutterBottom>
                Langue et Région
              </Typography>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                Personnalisez vos préférences d&apos;affichage
              </Typography>
            </Box>
          </Stack>
          
          <ConditionalComponent isValid={!isEditing}>
            <EditExportButtons
              onEdit={handleEdit}
              tooltipTitle="les paramètres de langue"
            />
          </ConditionalComponent>
        </Stack>

        <ConditionalComponent 
          isValid={isEditing}
          defaultComponent={<ViewMode />}
        >
          {renderEditMode()}
        </ConditionalComponent>
      </Card>
    </Stack>
  );
}