'use client';

import React, { useState, useEffect } from 'react';
import { Button } from '@alga-psa/ui/components/Button';
import { Input } from '@alga-psa/ui/components/Input';
import { Label } from '@alga-psa/ui/components/Label';
import { TextArea } from '@alga-psa/ui/components/TextArea';
import { Switch } from '@alga-psa/ui/components/Switch';
import CustomSelect from '@alga-psa/ui/components/CustomSelect';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import { 
  createInboundTicketDefaults, 
  updateInboundTicketDefaults 
} from '@alga-psa/integrations/actions';
import { getAvailableStatuses, getTicketFieldOptions, getCategoriesByBoard } from '@alga-psa/integrations/actions';
import type { InboundTicketDefaults, TicketFieldOptions } from '@alga-psa/types';
import { ClientPicker } from '@alga-psa/ui/components/ClientPicker';
import { PrioritySelect } from '@alga-psa/ui/components';
import UserPicker from '@alga-psa/ui/components/UserPicker';
import { getAllPriorities } from '@alga-psa/reference-data/actions';
import { getAllUsersBasic, getUserAvatarUrlsBatchAction } from '@alga-psa/user-composition/actions';
import type { IPriority } from '@alga-psa/types';
import type { IClient } from '@alga-psa/types';
import type { IUser } from '@shared/interfaces/user.interfaces';
import { getIntegrationClients } from '../../../actions/clientLookupActions';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

export interface InboundTicketDefaultsFormProps {
  defaults?: InboundTicketDefaults | null;
  onSuccess: (defaults: InboundTicketDefaults) => void;
  onCancel: () => void;
}

export function InboundTicketDefaultsForm({ 
  defaults, 
  onSuccess, 
  onCancel 
}: InboundTicketDefaultsFormProps) {
  const { t } = useTranslation('msp/email-providers');
  const [formData, setFormData] = useState({
    short_name: '',
    display_name: '',
    description: '',
    is_active: true,
    board_id: '',
    status_id: '',
    priority_id: '',
    client_id: '',
    category_id: '',
    subcategory_id: '',
    location_id: '',
    entered_by: null as string | null
  });
  
  const [fieldOptions, setFieldOptions] = useState<TicketFieldOptions>({
    boards: [],
    statuses: [],
    priorities: [],
    categories: [],
    clients: [],
    users: [],
    locations: []
  });
  
  const [loading, setLoading] = useState(false);
  const [loadingOptions, setLoadingOptions] = useState(true);
  const [loadingStatuses, setLoadingStatuses] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [clients, setClients] = useState<IClient[]>([]);
  const [priorities, setPriorities] = useState<IPriority[]>([]);
  const [usersWithRoles, setUsersWithRoles] = useState<IUser[]>([]);
  const [clientFilterState, setClientFilterState] = useState<'all' | 'active' | 'inactive'>('all');
  const [clientTypeFilter, setClientTypeFilter] = useState<'all' | 'company' | 'individual'>('all');

  // Load field options on mount
  useEffect(() => {
    loadFieldOptions();
  }, []);

  // Load categories when board changes (server-side filtered)
  useEffect(() => {
    const loadCategoriesForBoard = async () => {
      if (!formData.board_id) {
        // Clear categories if no board selected
        setFieldOptions(prev => ({ ...prev, categories: [] }));
        return;
      }
      try {
        const { categories } = await getCategoriesByBoard(formData.board_id);
        setFieldOptions(prev => ({ ...prev, categories }));
      } catch (err) {
        // On error, keep categories empty for safety
        setFieldOptions(prev => ({ ...prev, categories: [] }));
      }
    };
    loadCategoriesForBoard();
  }, [formData.board_id]);

  useEffect(() => {
    let active = true;

    const loadStatusesForBoard = async () => {
      if (!formData.board_id) {
        setFieldOptions(prev => ({ ...prev, statuses: [] }));
        return;
      }

      try {
        setLoadingStatuses(true);
        const { statuses } = await getAvailableStatuses(formData.board_id);
        if (!active) {
          return;
        }

        setFieldOptions(prev => ({ ...prev, statuses }));
        setFormData(prev => {
          if (!prev.status_id) {
            return prev;
          }

          const hasSelectedStatus = statuses.some(status => status.id === prev.status_id);
          return hasSelectedStatus ? prev : { ...prev, status_id: '' };
        });
      } catch (_err) {
        if (!active) {
          return;
        }

        setFieldOptions(prev => ({ ...prev, statuses: [] }));
        setFormData(prev => (prev.status_id ? { ...prev, status_id: '' } : prev));
      } finally {
        if (active) {
          setLoadingStatuses(false);
        }
      }
    };

    loadStatusesForBoard();

    return () => {
      active = false;
    };
  }, [formData.board_id]);

  // Populate form when editing
  useEffect(() => {
    if (defaults) {
      setFormData({
        short_name: defaults.short_name,
        display_name: defaults.display_name,
        description: defaults.description || '',
        is_active: defaults.is_active,
        board_id: defaults.board_id || '',
        status_id: defaults.status_id || '',
        priority_id: defaults.priority_id || '',
        client_id: defaults.client_id || '',
        category_id: defaults.category_id || '',
        subcategory_id: defaults.subcategory_id || '',
        location_id: defaults.location_id || '',
        entered_by: defaults.entered_by || null
      });
    }
  }, [defaults]);

  const loadFieldOptions = async () => {
    try {
      setLoadingOptions(true);
      const data = await getTicketFieldOptions();
      setFieldOptions({
        ...data.options,
        statuses: [],
        categories: [],
      });

      // Hydrate dedicated pickers with richer datasets
      const [allClients, allPriorities, allUsers] = await Promise.all([
        getIntegrationClients(true),
        getAllPriorities('ticket'),
        getAllUsersBasic(true, 'internal')
      ]);
      setClients(allClients || []);
      setPriorities((allPriorities as IPriority[]) || []);
      setUsersWithRoles(allUsers || []);
    } catch (err: any) {
      setError(t('inboundDefaultsForm.feedback.loadOptionsError', {
        defaultValue: 'Failed to load field options',
      }));
    } finally {
      setLoadingOptions(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.short_name.trim() || !formData.display_name.trim()) {
      setError(t('inboundDefaultsForm.validation.nameRequired', {
        defaultValue: 'Short name and display name are required',
      }));
      return;
    }

    if (!formData.board_id) {
      setError(t('inboundDefaultsForm.validation.boardRequired', {
        defaultValue: 'Board is required',
      }));
      return;
    }

    if (!formData.status_id) {
      setError(t('inboundDefaultsForm.validation.statusRequired', {
        defaultValue: 'Status is required',
      }));
      return;
    }

    if (!formData.priority_id) {
      setError(t('inboundDefaultsForm.validation.priorityRequired', {
        defaultValue: 'Priority is required',
      }));
      return;
    }

    // Client/Company is required
    if (!formData.client_id) {
      setError(t('inboundDefaultsForm.validation.clientRequired', {
        defaultValue: 'Company is required',
      }));
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const payload = {
        short_name: formData.short_name.trim(),
        display_name: formData.display_name.trim(),
        description: formData.description.trim() || undefined,
        is_active: formData.is_active,
        board_id: formData.board_id,
        status_id: formData.status_id,
        priority_id: formData.priority_id,
        client_id: formData.client_id || undefined,
        category_id: formData.category_id || undefined,
        subcategory_id: formData.subcategory_id || undefined,
        location_id: formData.location_id || undefined,
        entered_by: formData.entered_by || null
      };

      let result;
      if (defaults) {
        result = await updateInboundTicketDefaults(defaults.id, payload);
      } else {
        result = await createInboundTicketDefaults(payload);
      }

      onSuccess(result.defaults);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDefaultChange = (field: string, value: string | null) => {
    setFormData(prev => {
      const next = { ...prev, [field]: value } as typeof prev;
      // Clear dependent fields when parents change
      if (field === 'board_id') {
        next.status_id = '';
        next.category_id = '';
        next.subcategory_id = '';
      }
      if (field === 'category_id') {
        next.subcategory_id = '';
      }
      if (field === 'client_id' && prev.client_id !== value) {
        // Clear location if client changes
        next.location_id = '';
      }
      return next;
    });
  };

  if (loadingOptions) {
    return (
      <div className="flex items-center justify-center p-6">
        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
        <span className="ml-2">{t('inboundDefaultsForm.feedback.loading', {
          defaultValue: 'Loading form options...',
        })}</span>
      </div>
    );
  }

  const categoryOptions = (fieldOptions.categories || []).map((category) => ({
    value: category.id,
    label: category.parent_id ? `  - ${category.name}` : category.name,
  }));

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Error Alert */}
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* Basic Information */}
      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="short_name">{t('inboundDefaultsForm.fields.shortName.label', {
            defaultValue: 'Short Name *',
          })}</Label>
          <Input
            id="short_name"
            value={formData.short_name}
            onChange={(e) => setFormData(prev => ({ ...prev, short_name: e.target.value }))}
            placeholder={t('inboundDefaultsForm.fields.shortName.placeholder', {
              defaultValue: 'email-general',
            })}
            required
          />
          <p className="text-xs text-muted-foreground mt-1">
            {t('inboundDefaultsForm.fields.shortName.help', {
              defaultValue: 'Unique identifier (e.g., email-general, support-billing)',
            })}
          </p>
        </div>

        <div>
          <Label htmlFor="display_name">{t('inboundDefaultsForm.fields.displayName.label', {
            defaultValue: 'Display Name *',
          })}</Label>
          <Input
            id="display_name"
            value={formData.display_name}
            onChange={(e) => setFormData(prev => ({ ...prev, display_name: e.target.value }))}
            placeholder={t('inboundDefaultsForm.fields.displayName.placeholder', {
              defaultValue: 'General Email Support',
            })}
            required
          />
        </div>
      </div>

      <div>
        <Label htmlFor="description">{t('inboundDefaultsForm.fields.description.label', {
          defaultValue: 'Description',
        })}</Label>
        <TextArea
          id="description"
          value={formData.description}
          onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
          placeholder={t('inboundDefaultsForm.fields.description.placeholder', {
            defaultValue: 'Optional description of when these defaults are used',
          })}
          rows={2}
        />
      </div>

      <div className="flex items-center space-x-2">
        <Switch
          id="is_active"
          checked={formData.is_active}
          onCheckedChange={(checked) => setFormData(prev => ({ ...prev, is_active: checked }))}
        />
        <Label htmlFor="is_active">{t('inboundDefaultsForm.fields.active.label', {
          defaultValue: 'Active',
        })}</Label>
      </div>

      {/* Ticket Defaults */}
      <div className="border-t pt-6">
        <h4 className="text-lg font-medium mb-4">{t('inboundDefaultsForm.section.ticketDefaults', {
          defaultValue: 'Ticket Defaults',
        })}</h4>
        
        <div className="grid grid-cols-2 gap-4">
          {/* Required Fields */}
          <div>
            <Label htmlFor="board_id">{t('inboundDefaultsForm.fields.board.label', {
              defaultValue: 'Board *',
            })}</Label>
            <CustomSelect
              id="board_id"
              value={formData.board_id}
              onValueChange={(value) => handleDefaultChange('board_id', value)}
              options={fieldOptions.boards.map((board) => ({
                value: board.id,
                label: board.name + (board.is_default ? ` ${t('inboundDefaultsForm.optionSuffix.default', {
                  defaultValue: '(Default)',
                })}` : ''),
              }))}
              placeholder={t('inboundDefaultsForm.fields.board.placeholder', {
                defaultValue: 'Select Board',
              })}
            />
          </div>

          <div>
            <Label htmlFor="status_id">{t('inboundDefaultsForm.fields.status.label', {
              defaultValue: 'Status *',
            })}</Label>
            <CustomSelect
              id="status_id"
              value={formData.status_id}
              onValueChange={(value) => handleDefaultChange('status_id', value)}
              options={fieldOptions.statuses.map(s => ({ 
                value: s.id, 
                label: s.name + (s.is_default ? ` ${t('inboundDefaultsForm.optionSuffix.default', {
                  defaultValue: '(Default)',
                })}` : '')
              }))}
              placeholder={
                !formData.board_id
                  ? t('inboundDefaultsForm.fields.status.selectBoardFirst', {
                      defaultValue: 'Select board first',
                    })
                  : (loadingStatuses
                      ? t('inboundDefaultsForm.fields.status.loading', {
                          defaultValue: 'Loading statuses...',
                        })
                      : t('inboundDefaultsForm.fields.status.placeholder', {
                          defaultValue: 'Select status',
                        }))
              }
              disabled={!formData.board_id || loadingStatuses}
            />
          </div>

          <div>
            <Label htmlFor="priority_id">{t('inboundDefaultsForm.fields.priority.label', {
              defaultValue: 'Priority *',
            })}</Label>
            <PrioritySelect
              id="priority_id"
              value={formData.priority_id}
              onValueChange={(value) => handleDefaultChange('priority_id', value)}
              options={priorities.map(p => ({ 
                value: p.priority_id, 
                label: p.priority_name, 
                color: p.color 
              }))}
              placeholder={t('inboundDefaultsForm.fields.priority.placeholder', {
                defaultValue: 'Select priority',
              })}
            />
          </div>

          {/* Optional Fields */}
          <div>
            <Label htmlFor="client_id">{t('inboundDefaultsForm.fields.client.label', {
              defaultValue: 'Client *',
            })}</Label>
            <ClientPicker
              id="client_id"
              clients={clients}
              selectedClientId={formData.client_id || null}
              onSelect={(clientId) => handleDefaultChange('client_id', clientId || '')}
              filterState={clientFilterState}
              onFilterStateChange={setClientFilterState}
              clientTypeFilter={clientTypeFilter}
              onClientTypeFilterChange={setClientTypeFilter}
              placeholder={t('inboundDefaultsForm.fields.client.placeholder', {
                defaultValue: 'Select Client',
              })}
            />
            <p className="text-xs text-muted-foreground mt-1">
              {t('inboundDefaultsForm.fields.client.help', {
                defaultValue: 'Required: used as a catch-all when no client can be matched from the email.',
              })}
            </p>
          </div>

          <div>
            <Label htmlFor="category_id">{t('inboundDefaultsForm.fields.category.label', {
              defaultValue: 'Category',
            })}</Label>
            <CustomSelect
              id="category_id"
              value={formData.subcategory_id || formData.category_id}
              onValueChange={(selectedId) => {
                if (!selectedId) {
                  handleDefaultChange('category_id', '');
                  handleDefaultChange('subcategory_id', '');
                  return;
                }
                const found = fieldOptions.categories.find(c => c.id === selectedId);
                if (found?.parent_id) {
                  // Selected a subcategory
                  handleDefaultChange('category_id', found.parent_id);
                  handleDefaultChange('subcategory_id', found.id);
                } else {
                  // Selected a top-level category
                  handleDefaultChange('category_id', selectedId);
                  handleDefaultChange('subcategory_id', '');
                }
              }}
              options={categoryOptions}
              placeholder={formData.board_id
                ? t('inboundDefaultsForm.fields.category.placeholder', {
                  defaultValue: 'Select category',
                })
                : t('inboundDefaultsForm.fields.category.placeholderNoBoard', {
                  defaultValue: 'Select board first',
                })}
              disabled={!formData.board_id}
              allowClear
            />
            {formData.board_id && (fieldOptions.categories || []).filter(c => !c.parent_id && String(c.board_id || '') === String(formData.board_id)).length === 0 && (
              <p className="text-xs text-muted-foreground mt-1">{t('inboundDefaultsForm.fields.category.empty', {
                defaultValue: 'No categories found for the selected board.',
              })}</p>
            )}
          </div>

          <div>
            <Label htmlFor="location_id">{t('inboundDefaultsForm.fields.location.label', {
              defaultValue: 'Location',
            })}</Label>
            <CustomSelect
              id="location_id"
              value={formData.location_id}
              onValueChange={(value) => handleDefaultChange('location_id', value || '')}
              options={fieldOptions.locations
                .filter(l => !formData.client_id || l.client_id === formData.client_id)
                .map(l => ({ value: l.id, label: l.name }))}
              placeholder={formData.client_id
                ? t('inboundDefaultsForm.fields.location.placeholder', {
                  defaultValue: 'Select location',
                })
                : t('inboundDefaultsForm.fields.location.placeholderNoClient', {
                  defaultValue: 'Select client first (optional)',
                })}
              disabled={!formData.client_id}
              allowClear
            />
            <p className="text-xs text-muted-foreground mt-1">
              {t('inboundDefaultsForm.fields.location.help', {
                defaultValue: 'Only applied when the catch-all client is used (no match case).',
              })}
            </p>
          </div>

          <div>
            <Label htmlFor="entered_by">{t('inboundDefaultsForm.fields.enteredBy.label', {
              defaultValue: 'Entered By',
            })}</Label>
            <UserPicker
              label={undefined}
              value={formData.entered_by || ''}
              onValueChange={(value) => handleDefaultChange('entered_by', value || null)}
              users={usersWithRoles}
              getUserAvatarUrlsBatch={getUserAvatarUrlsBatchAction}
              placeholder={t('inboundDefaultsForm.fields.enteredBy.placeholder', {
                defaultValue: 'System (null)',
              })}
              userTypeFilter="internal"
              buttonWidth="full"
            />
            <p className="text-xs text-muted-foreground mt-1">
              {t('inboundDefaultsForm.fields.enteredBy.help', {
                defaultValue: 'Used only when we cannot match a contact or client. System tickets will show "System" as creator.',
              })}
            </p>
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="flex justify-end gap-3 pt-6 border-t">
        <Button id="cancel-button" type="button" variant="outline" onClick={onCancel} disabled={loading}>
          {t('inboundDefaultsForm.actions.cancel', {
            defaultValue: 'Cancel',
          })}
        </Button>
        <Button id="submit-button" type="submit" disabled={loading}>
          {loading ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              {defaults
                ? t('inboundDefaultsForm.actions.updating', {
                  defaultValue: 'Updating...',
                })
                : t('inboundDefaultsForm.actions.creating', {
                  defaultValue: 'Creating...',
                })}
            </>
          ) : (
            defaults
              ? t('inboundDefaultsForm.actions.update', {
                defaultValue: 'Update Defaults',
              })
              : t('inboundDefaultsForm.actions.create', {
                defaultValue: 'Create Defaults',
              })
          )}
        </Button>
      </div>
    </form>
  );
}
