'use client';

import React, { useState, useEffect } from 'react';
import { IProject } from '@alga-psa/types';
import { IStatus } from '@alga-psa/types';
import { IClient } from '@alga-psa/types';
import { IUser } from '@shared/interfaces/user.interfaces';
import { ITag } from '@alga-psa/types';
import { Button } from '@alga-psa/ui/components/Button';
import { Switch } from '@alga-psa/ui/components/Switch';
import { TextArea } from '@alga-psa/ui/components/TextArea';
import { Input } from '@alga-psa/ui/components/Input';
import { DatePicker } from '@alga-psa/ui/components/DatePicker';
import { ClientPicker } from '@alga-psa/ui/components/ClientPicker';
import UserPicker from '@alga-psa/ui/components/UserPicker';
import CustomSelect, { SelectOption } from '@alga-psa/ui/components/CustomSelect';
import { TagManager } from '@alga-psa/tags/components';
import { updateProject, getProjectStatuses } from '../actions/projectActions';
import { getAllUsersBasic, getUserAvatarUrlsBatchAction } from '@alga-psa/user-composition/actions';
import { useClientIntegration } from '../context/ClientIntegrationContext';
import { findTagsByEntityId } from '@alga-psa/tags/actions';
import { useTagPermissions } from '@alga-psa/tags/hooks';
import { toast } from 'react-hot-toast';
import { handleError, isActionPermissionError } from '@alga-psa/ui/lib/errorHandling';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import { ProjectTaskStatusSettings } from './settings/projects/ProjectTaskStatusSettings';
import { Dialog } from '@alga-psa/ui/components/Dialog';
import ClientPortalConfigEditor from './ClientPortalConfigEditor';
import { DEFAULT_CLIENT_PORTAL_CONFIG } from '@alga-psa/types';
import { ChevronDown, ChevronRight, Settings } from 'lucide-react';
import { useTranslation } from 'react-i18next';

interface ProjectDetailsEditProps {
  initialProject: IProject;
  clients: IClient[];
  onSave: (updatedProject: IProject) => void;
  onCancel: () => void;
  onChange?: () => void;
}

const ProjectDetailsEdit: React.FC<ProjectDetailsEditProps> = ({
  initialProject,
  clients,
  onSave,
  onCancel,
}) => {
  const { t } = useTranslation(['features/projects', 'common']);
  const { getContactsByClient, getAllContacts } = useClientIntegration();
  // Initialize tag permissions for project tags
  useTagPermissions(['project']);
  
  // Debug logs
  useEffect(() => {
    console.log('ProjectDetailsEdit:', {
      initialProject,
      clientsLength: clients?.length,
      clients
    });
  }, [initialProject, clients]);

  const [project, setProject] = useState<IProject>(initialProject);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [showSaveConfirm, setShowSaveConfirm] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [contacts, setContacts] = useState<{ value: string; label: string }[]>([]);
  const [users, setUsers] = useState<IUser[]>([]);
  const [statuses, setStatuses] = useState<IStatus[]>([]);
  const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
  const [validationErrors, setValidationErrors] = useState<string[]>([]);
  const [projectTags, setProjectTags] = useState<ITag[]>([]);
  const [showClientPortalConfig, setShowClientPortalConfig] = useState(false);
  
  // TagContext is available if needed for tag-related features in the future
  // const { tags } = useTags();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [allUsers, projectStatusesResult, projectTagsData] = await Promise.all([
          getAllUsersBasic(),
          getProjectStatuses(),
          initialProject.project_id ? findTagsByEntityId(initialProject.project_id, 'project') : Promise.resolve([])
        ]);
        setUsers(allUsers);
        if (isActionPermissionError(projectStatusesResult)) {
          handleError(projectStatusesResult.permissionError);
          return;
        }
        setStatuses(projectStatusesResult);
        setProjectTags(projectTagsData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [initialProject.project_id]);

  useEffect(() => {
    const fetchContacts = async () => {
      try {
        const contactsData = project.client_id 
          ? await getContactsByClient(project.client_id)
          : await getAllContacts();
          setContacts(contactsData.map((contact): { value: string; label: string } => ({
            value: contact.contact_name_id,
            label: contact.full_name
        })));
      } catch (error) {
        console.error('Error fetching contacts:', error);
        setContacts([]);
      }
    };
    fetchContacts();
  }, [project.client_id]);

  const clearErrorIfSubmitted = () => {
    if (hasAttemptedSubmit) {
      setValidationErrors([]);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setHasAttemptedSubmit(true);

    // Validate required fields
    const errors: string[] = [];
    if (!project.project_name?.trim()) {
      errors.push(t('fields.projectName', 'Project Name'));
    }
    if (!project.status) {
      errors.push(t('fields.status', 'Status'));
    }
    if (!project.client_id) {
      errors.push(t('projectList.columns.client', 'Client'));
    }

    if (errors.length > 0) {
      setValidationErrors(errors);
      return;
    }

    setValidationErrors([]);
    setIsSubmitting(true);

    try {
      // Convert budgeted_hours to a number or null
      const budgetedHours = project.budgeted_hours ? Number(project.budgeted_hours) : null;
      
      const updatedProject = await updateProject(project.project_id, {
        project_name: project.project_name,
        description: project.description,
        client_id: project.client_id,
        start_date: project.start_date,
        end_date: project.end_date,
        assigned_to: project.assigned_to,
        contact_name_id: project.contact_name_id,
        is_inactive: project.is_inactive,
        status: project.status,
        budgeted_hours: budgetedHours,
        client_portal_config: project.client_portal_config,
      });
      if (isActionPermissionError(updatedProject)) {
        handleError(updatedProject.permissionError);
        return;
      }

      // Log for debugging
      console.log('Updated project with budgeted hours:', budgetedHours);

      toast.success(t('projectEdit.updatedSuccess', 'Project updated successfully'));
      onSave(updatedProject);
    } catch (error) {
      const errorMessage = error instanceof Error
        ? error.message
        : t('projectEdit.updateError', 'Failed to update project');
      setValidationErrors([errorMessage]);
      handleError(error, t('projectEdit.updateError', 'Failed to update project'));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setProject(prev => ({
      ...prev,
      [name]: value,
    }));
    setHasChanges(true);
    clearErrorIfSubmitted();
  };

  const handleClientSelect = (clientId: string | null) => {
    setProject(prev => ({
      ...prev,
      client_id: clientId || '',
      // Reset contact when client changes
      contact_name_id: null,
      contact_name: null,
    }));
    setHasChanges(true);
    clearErrorIfSubmitted();
  };

  return (
    <div className="p-4 w-full max-w-[480px] mx-auto">
      <form onSubmit={handleSubmit} className="space-y-4" noValidate>
        {hasAttemptedSubmit && validationErrors.length > 0 && (
          <Alert variant="destructive">
            <AlertDescription>
              <p className="font-medium mb-2">{t('projectEdit.validationTitle', 'Please fill in the required fields:')}</p>
              <ul className="list-disc list-inside space-y-1">
                {validationErrors.map((err, index) => (
                  <li key={index}>{err}</li>
                ))}
              </ul>
            </AlertDescription>
          </Alert>
        )}
        <div className="space-y-3">
          <div>
            <label htmlFor="project_name" className="block text-sm font-medium text-gray-700 mb-1">
              {t('projectEdit.projectNameLabel', 'Project Name *')}
            </label>
            <TextArea
              id="project_name"
              name="project_name"
              value={project.project_name}
              onChange={handleInputChange}
              placeholder={t('projectEdit.projectNamePlaceholder', 'Enter project name...')}
              className={`w-full text-base font-medium p-2 border rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-purple-500 ${
                hasAttemptedSubmit && !project.project_name?.trim() ? 'border-destructive' : 'border-gray-300'
              }`}
              rows={1}
              required
            />
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
              {t('fields.description', 'Description')}
            </label>
            <TextArea
              id="description"
              name="description"
              value={project.description || ''}
              onChange={handleInputChange}
              placeholder={t('projectEdit.descriptionPlaceholder', 'Enter project description...')}
              className="w-full text-sm p-2 border border-gray-300 rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-purple-500"
              rows={3}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('projectEdit.statusLabel', 'Status *')}</label>
            <CustomSelect
              value={project.status}
              onValueChange={(value) => {
                setProject(prev => ({ ...prev, status: value }));
                setHasChanges(true);
                clearErrorIfSubmitted();
              }}
              options={statuses.map((status): SelectOption => ({
                value: status.status_id,
                label: status.name
              }))}
              placeholder={t('projectEdit.statusPlaceholder', 'Select Status')}
              className={hasAttemptedSubmit && !project.status ? 'ring-1 ring-red-500' : ''}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {t('quickAdd.clientLabel', 'Client *')}
            </label>
            <ClientPicker
              id='client-picker'
              clients={clients}
              selectedClientId={project.client_id}
              onSelect={handleClientSelect}
              filterState="all"
              onFilterStateChange={() => {}}
              clientTypeFilter="all"
              onClientTypeFilterChange={() => {}}
              className={hasAttemptedSubmit && !project.client_id ? 'ring-1 ring-red-500 rounded-md' : ''}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('projectEdit.contactLabel', 'Contact')}</label>
            <CustomSelect
              value={project.contact_name_id || ''}
              onValueChange={(value) => {
                setProject(prev => ({ ...prev, contact_name_id: value }));
                setHasChanges(true);
                clearErrorIfSubmitted();
              }}
              options={contacts}
              placeholder={t('projectEdit.contactPlaceholder', 'Select Contact')}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {t('fields.projectManager', 'Project Manager')}
            </label>
            <UserPicker
              value={project.assigned_to || ''}
              onValueChange={(value) => {
                setProject(prev => ({ ...prev, assigned_to: value || null }));
                setHasChanges(true);
                clearErrorIfSubmitted();
              }}
              users={users}
              getUserAvatarUrlsBatch={getUserAvatarUrlsBatchAction}
              size="sm"
              labelStyle="none"
              buttonWidth="full"
            />
          </div>

          <div>
            <label htmlFor="budgeted_hours" className="block text-sm font-medium text-gray-700 mb-1">
              {t('projectEdit.budgetedHoursLabel', 'Budgeted Hours')}
            </label>
            <Input
              id="budgeted_hours"
              name="budgeted_hours"
              type="number"
              // Convert from minutes to hours for display
              value={project.budgeted_hours ? (project.budgeted_hours / 60).toString() : ''}
              onChange={(e) => {
                const { name, value } = e.target;
                // Only allow numbers and decimal point, prevent 'e'
                if (value === '' || (/^\d*\.?\d*$/.test(value) && !value.includes('e'))) {
                  const hoursValue = parseFloat(value);
                  const minutesValue = value ? Math.round(hoursValue * 60) : null; // Store null if empty
                  setProject(prev => ({
                    ...prev,
                    // Convert from hours to minutes for storage
                    [name]: minutesValue,
                  }));
                  setHasChanges(true);
                  clearErrorIfSubmitted();
                }
              }}
              onKeyDown={(e) => {
                // Prevent 'e' character from being entered
                if (e.key === 'e' || e.key === 'E') {
                  e.preventDefault();
                }
              }}
              min="0"
              step="0.25" // Allow quarter-hour increments
              placeholder={t('projectEdit.budgetedHoursPlaceholder', 'Enter budgeted hours')}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('projectEdit.tagsLabel', 'Tags')}</label>
            <TagManager
              id="project-tags-edit"
              entityId={project.project_id}
              entityType="project"
              initialTags={projectTags}
              onTagsChange={(tags) => {
                console.log('Tags changed in ProjectDetailsEdit:', tags);
                setProjectTags(tags);
                setHasChanges(true);
              }}
              useInlineInput={true}
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label htmlFor="start_date" className="block text-sm font-medium text-gray-700 mb-1">
                {t('fields.startDate', 'Start Date')}
              </label>
              <DatePicker
                id="start_date"
                value={project.start_date ? new Date(project.start_date) : undefined}
                onChange={(date) => {
                  setProject(prev => ({
                    ...prev,
                    start_date: date || null,
                  }));
                  setHasChanges(true);
                  clearErrorIfSubmitted();
                }}
                placeholder={t('projectEdit.startDatePlaceholder', 'Select start date')}
              />
            </div>

            <div>
              <label htmlFor="end_date" className="block text-sm font-medium text-gray-700 mb-1">
                {t('fields.endDate', 'End Date')}
              </label>
              <DatePicker
                id="end_date"
                value={project.end_date ? new Date(project.end_date) : undefined}
                onChange={(date) => {
                  setProject(prev => ({
                    ...prev,
                    end_date: date || null,
                  }));
                  setHasChanges(true);
                  clearErrorIfSubmitted();
                }}
                placeholder={t('projectEdit.endDatePlaceholder', 'Select end date')}
              />
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <span className={`px-2 py-1 rounded text-sm ${project.is_inactive ? 'text-gray-800' : 'text-gray-800'}`}>
              {project.is_inactive
                ? t('common:status.inactive', 'Inactive')
                : t('common:status.active', 'Active')}
            </span>
            <Switch
              id="is_inactive"
              checked={!project.is_inactive}
              onCheckedChange={(checked) => {
                setProject(prev => ({ ...prev, is_inactive: !checked }));
                setHasChanges(true);
                clearErrorIfSubmitted();
              }}
            />
          </div>

          <div>
            <ProjectTaskStatusSettings
              projectId={project.project_id}
            />
          </div>

          {/* Client Portal Visibility - Expandable Section */}
          <div className="border-t pt-4 mt-4">
            <button
              type="button"
              onClick={() => setShowClientPortalConfig(!showClientPortalConfig)}
              className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-gray-900"
            >
              {showClientPortalConfig ? (
                <ChevronDown className="h-4 w-4" />
              ) : (
                <ChevronRight className="h-4 w-4" />
              )}
              <Settings className="h-4 w-4" />
              <span>{t('projectEdit.clientPortalVisibility', 'Client Portal Visibility')}</span>
            </button>
            {showClientPortalConfig && (
              <div className="mt-3">
                <ClientPortalConfigEditor
                  config={project.client_portal_config || DEFAULT_CLIENT_PORTAL_CONFIG}
                  onChange={(config) => {
                    setProject(prev => ({ ...prev, client_portal_config: config }));
                    setHasChanges(true);
                  }}
                  disabled={isSubmitting}
                />
              </div>
            )}
          </div>
        </div>

        <div className="flex justify-end space-x-3 mt-4">
          <Dialog
            isOpen={showCancelConfirm}
            onClose={() => setShowCancelConfirm(false)}
            title={t('projectEdit.unsavedTitle', 'Unsaved Changes')}
            id="cancel-confirm-dialog"
            className="max-w-md"
            draggable={false}
            footer={
              <div className="flex justify-end space-x-3">
                <Button
                  id="cancel-button"
                  type="button"
                  variant="outline"
                  onClick={() => setShowCancelConfirm(false)}
                >
                  {t('projectEdit.continueEditing', 'Continue Editing')}
                </Button>
                <Button
                  id="discard-button"
                  type="button"
                  onClick={() => {
                    setShowCancelConfirm(false);
                    onCancel();
                  }}
                >
                  {t('projectEdit.discardChanges', 'Discard Changes')}
                </Button>
              </div>
            }
          >
            <p className="mb-4">{t('projectEdit.unsavedMessage', 'You have unsaved changes. Are you sure you want to cancel?')}</p>
          </Dialog>

          <Dialog
            isOpen={showSaveConfirm}
            onClose={() => setShowSaveConfirm(false)}
            title={t('projectEdit.saveTitle', 'Save Changes')}
            id="save-confirm-dialog"
            className="max-w-md"
            draggable={false}
            footer={
              <div className="flex justify-end space-x-3">
                <Button
                  id="continue-button"
                  type="button"
                  variant="outline"
                  onClick={() => setShowSaveConfirm(false)}
                >
                  {t('projectEdit.continueEditing', 'Continue Editing')}
                </Button>
                <Button
                  id="save-and-close-button"
                  type="button"
                  onClick={(e) => {
                    setShowSaveConfirm(false);
                    handleSubmit(e);
                  }}
                >
                  {t('projectEdit.saveAndClose', 'Save and Close')}
                </Button>
              </div>
            }
          >
            <p className="mb-4">{t('projectEdit.saveMessage', 'Are you sure you want to save your changes and close the drawer?')}</p>
          </Dialog>

          <Button
            id='cancel-button'
            type="button"
            variant="outline"
            onClick={() => {
              if (hasChanges) {
                setShowCancelConfirm(true);
              } else {
                onCancel();
              }
            }}
            disabled={isSubmitting}
          >
            {t('common:actions.cancel', 'Cancel')}
          </Button>
          <Button
            id='save-button'
            type="button"
            onClick={() => setShowSaveConfirm(true)}
            disabled={isSubmitting}
            className={!project.project_name?.trim() || !project.status || !project.client_id ? 'opacity-50' : ''}
          >
            {isSubmitting
              ? t('projectEdit.saving', 'Saving...')
              : t('projectEdit.saveTitle', 'Save Changes')}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default ProjectDetailsEdit;
