'use client'

import { Edit3, Save, AlertTriangle, CheckCircle } from 'lucide-react'
import React, { useState, useEffect, useRef, useCallback } from 'react'

import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useSidebar } from '@/hooks/useSidebar'

import { Sidebar } from '../sidebar'

import { ContactsBlock } from './blocks/ContactsBlock'
import { FinancialBlock } from './blocks/FinancialBlock'
import { IntegrationsBlock } from './blocks/IntegrationsBlock'
import { LegalBlock } from './blocks/LegalBlock'
import { MarketBlock } from './blocks/MarketBlock'
import { OrganizationBlock } from './blocks/OrganizationBlock'
import { ProfileBlock } from './blocks/ProfileBlock'
import { useContactsSettings } from './hooks/useContactsSettings'
import { useFinancialSettings } from './hooks/useFinancialSettings'
import { useOrganizationSettings } from './hooks/useOrganizationSettings'
import { useProfileSettings } from './hooks/useProfileSettings'
import type { UserData, UserSettingsFormData } from './types/user-settings.types'

export function UserSettings() {
  const { getSidebarMargin } = useSidebar()

  // State management
  const [isEditing, setIsEditing] = useState(false)
  const [formData, setFormData] = useState<UserSettingsFormData>({
    orgPhone: '+7',
    managerName: '',
    telegram: '',
    whatsapp: '',
    email: '',
    orgName: '',
    address: '',
    fullName: '',
    inn: '',
    ogrn: '',
    registrationPlace: '',
    bankName: '',
    bik: '',
    accountNumber: '',
    corrAccount: '',
    wildberriesApiKey: '',
    ozonApiKey: '',
    market: 'none',
  })

  // Refs for inputs
  const phoneInputRef = useRef<HTMLInputElement | null>(null)
  const whatsappInputRef = useRef<HTMLInputElement | null>(null)

  // Initialize hooks
  const profileSettings = useProfileSettings()
  const organizationSettings = useOrganizationSettings()
  const contactsSettings = useContactsSettings()
  const financialSettings = useFinancialSettings()

  // Initialize form data on component mount
  useEffect(() => {
    const initialData = organizationSettings.initializeFormData()
    setFormData(initialData)
  }, [organizationSettings])

  // Profile completeness calculation
  const checkProfileCompleteness = useCallback(() => {
    const baseFields = [
      { field: 'orgPhone', label: 'Телефон организации', value: formData.orgPhone },
      { field: 'managerName', label: 'Имя управляющего', value: formData.managerName },
      { field: 'email', label: 'Email', value: formData.email },
    ]

    const additionalFields = []
    if (
      profileSettings.user?.organization?.type &&
      ['FULFILLMENT', 'LOGIST', 'WHOLESALE', 'SELLER'].includes(profileSettings.user.organization.type)
    ) {
      additionalFields.push(
        { field: 'bankName', label: 'Название банка', value: formData.bankName },
        { field: 'bik', label: 'БИК', value: formData.bik },
        { field: 'accountNumber', label: 'Расчетный счет', value: formData.accountNumber },
        { field: 'corrAccount', label: 'Корр. счет', value: formData.corrAccount },
      )
    }

    const allRequiredFields = [...baseFields, ...additionalFields]
    const filledRequiredFields = allRequiredFields.filter(
      (field) => field.value && field.value.trim() !== '' && field.value !== '+7',
    ).length

    // Count auto-filled fields
    let autoFilledFields = 0
    let totalAutoFields = 0

    if (formData.inn || profileSettings.user?.organization?.inn) {
      totalAutoFields += 5
      if (formData.inn || profileSettings.user?.organization?.inn) autoFilledFields += 1
      if (formData.orgName || profileSettings.user?.organization?.name) autoFilledFields += 1
      if (formData.address || profileSettings.user?.organization?.address) autoFilledFields += 1
      if (formData.fullName || profileSettings.user?.organization?.fullName) autoFilledFields += 1
      if (formData.ogrn || profileSettings.user?.organization?.ogrn) autoFilledFields += 1
    }

    if (formData.registrationPlace) {
      autoFilledFields += 1
      totalAutoFields += 1
    }

    const totalPossibleFields = allRequiredFields.length + totalAutoFields
    const totalFilledFields = filledRequiredFields + autoFilledFields
    const percentage = totalPossibleFields > 0 ? Math.round((totalFilledFields / totalPossibleFields) * 100) : 0

    const missingFields = allRequiredFields
      .filter((field) => !field.value || field.value.trim() === '' || field.value === '+7')
      .map((field) => field.label)

    return { percentage, missingFields }
  }, [formData, profileSettings.user])

  const profileStatus = checkProfileCompleteness()
  const isIncomplete = profileStatus.percentage < 100

  // Form validation
  const hasFormChanges = useCallback(() => {
    if (!profileSettings.user?.organization) return false

    const initialData = organizationSettings.initializeFormData()

    return Object.keys(formData).some((key) => {
      const currentValue = formData[key as keyof UserSettingsFormData] || ''
      const initialValue = initialData[key as keyof UserSettingsFormData] || ''
      return currentValue !== initialValue
    })
  }, [formData, profileSettings.user, organizationSettings])

  const hasValidationErrors = useCallback(() => {
    const contactsValidation = contactsSettings.validateContactsData(formData)
    const financialValidation = financialSettings.validateFinancialData(formData)

    return !contactsValidation.isValid || !financialValidation.isValid
  }, [formData, contactsSettings, financialSettings])

  // DaData search handler
  const handleDaDataSearch = useCallback(
    async (inn: string) => {
      const orgData = await organizationSettings.searchDaData(inn)
      if (orgData) {
        setFormData((prev) => ({
          ...prev,
          ...orgData,
        }))
      }
    },
    [organizationSettings],
  )

  // Save handler
  const handleSave = useCallback(async () => {
    if (hasValidationErrors() || !hasFormChanges()) return

    const success = await organizationSettings.saveOrganizationData(formData)
    if (success) {
      setIsEditing(false)
    }
  }, [formData, hasValidationErrors, hasFormChanges, organizationSettings])

  // Clear all save messages
  const clearAllMessages = useCallback(() => {
    profileSettings.clearSaveMessage()
    organizationSettings.clearSaveMessage()
    contactsSettings.clearSaveMessage()
    financialSettings.clearSaveMessage()
  }, [profileSettings, organizationSettings, contactsSettings, financialSettings])

  // Get active save message
  const getActiveSaveMessage = () => {
    return (
      profileSettings.saveMessage ||
      organizationSettings.saveMessage ||
      contactsSettings.saveMessage ||
      financialSettings.saveMessage
    )
  }

  const activeSaveMessage = getActiveSaveMessage()

  return (
    <div className="flex h-screen bg-background">
      <Sidebar />

      <div className={`flex-1 ${getSidebarMargin()} transition-all duration-300`}>
        <div className="h-full flex flex-col">
          {/* Header */}
          <div className="flex-shrink-0 border-b border-border bg-background/95 backdrop-blur-sm">
            <div className="flex items-center justify-between p-6">
              <div>
                <h1 className="text-2xl font-bold text-foreground">Настройки профиля</h1>
                <p className="text-muted-foreground mt-1">Управление данными организации и интеграциями</p>
              </div>

              <div className="flex items-center space-x-4">
                {/* Profile completeness badge */}
                <div className="flex items-center space-x-2">
                  {isIncomplete ? (
                    <Badge variant="destructive" className="flex items-center space-x-1">
                      <AlertTriangle className="w-3 h-3" />
                      <span>Профиль заполнен на {profileStatus.percentage}%</span>
                    </Badge>
                  ) : (
                    <Badge
                      variant="default"
                      className="flex items-center space-x-1 bg-green-500/20 text-green-700 dark:text-green-400"
                    >
                      <CheckCircle className="w-3 h-3" />
                      <span>Профиль заполнен</span>
                    </Badge>
                  )}
                </div>

                {/* Edit/Save buttons */}
                {isEditing ? (
                  <div className="flex items-center space-x-2">
                    <Button
                      variant="outline"
                      onClick={() => {
                        setIsEditing(false)
                        clearAllMessages()
                        // Reset form data to initial state
                        const initialData = organizationSettings.initializeFormData()
                        setFormData(initialData)
                      }}
                    >
                      Отмена
                    </Button>
                    <Button
                      onClick={handleSave}
                      disabled={
                        hasValidationErrors() || organizationSettings.isUpdatingOrganization || !hasFormChanges()
                      }
                      className="flex items-center space-x-2"
                    >
                      <Save className="w-4 h-4" />
                      <span>{organizationSettings.isUpdatingOrganization ? 'Сохранение...' : 'Сохранить'}</span>
                    </Button>
                  </div>
                ) : (
                  <Button
                    onClick={() => {
                      setIsEditing(true)
                      clearAllMessages()
                    }}
                    className="flex items-center space-x-2"
                  >
                    <Edit3 className="w-4 h-4" />
                    <span>Редактировать</span>
                  </Button>
                )}
              </div>
            </div>

            {/* Save message */}
            {activeSaveMessage && (
              <div className="px-6 pb-4">
                <Alert
                  className={
                    activeSaveMessage.type === 'success'
                      ? 'border-green-500/50 bg-green-500/10'
                      : 'border-red-500/50 bg-red-500/10'
                  }
                >
                  <AlertDescription
                    className={
                      activeSaveMessage.type === 'success'
                        ? 'text-green-700 dark:text-green-400'
                        : 'text-red-700 dark:text-red-400'
                    }
                  >
                    {activeSaveMessage.text}
                  </AlertDescription>
                </Alert>
              </div>
            )}
          </div>

          {/* Content */}
          <div className="flex-1 overflow-hidden">
            <Tabs defaultValue="profile" className="h-full flex flex-col">
              <div className="flex-shrink-0 border-b border-border bg-background/95 backdrop-blur-sm">
                <TabsList className="w-full justify-start rounded-none bg-transparent p-0 h-auto">
                  <TabsTrigger
                    value="profile"
                    className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                  >
                    Профиль
                  </TabsTrigger>
                  <TabsTrigger
                    value="contacts"
                    className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                  >
                    Контакты
                  </TabsTrigger>
                  <TabsTrigger
                    value="organization"
                    className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                  >
                    Организация
                  </TabsTrigger>
                  <TabsTrigger
                    value="legal"
                    className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                  >
                    Юридические данные
                  </TabsTrigger>
                  {profileSettings.user?.organization?.type &&
                    ['FULFILLMENT', 'LOGIST', 'WHOLESALE', 'SELLER'].includes(
                      profileSettings.user.organization.type,
                    ) && (
                      <TabsTrigger
                        value="financial"
                        className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                      >
                        Финансы
                      </TabsTrigger>
                    )}
                  {profileSettings.user?.organization?.type === 'SELLER' && (
                    <TabsTrigger
                      value="integrations"
                      className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                    >
                      Интеграции
                    </TabsTrigger>
                  )}
                  {profileSettings.user?.organization?.type === 'WHOLESALE' && (
                    <TabsTrigger
                      value="market"
                      className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent"
                    >
                      Рынок
                    </TabsTrigger>
                  )}
                </TabsList>
              </div>

              <div className="flex-1 overflow-auto p-6">
                <TabsContent value="profile" className="mt-0 h-full">
                  <ProfileBlock
                    user={profileSettings.user as UserData | null}
                    localAvatarUrl={profileSettings.localAvatarUrl}
                    isUploadingAvatar={profileSettings.isUploadingAvatar}
                    onAvatarUpload={profileSettings.handleAvatarUpload}
                  />
                </TabsContent>

                <TabsContent value="contacts" className="mt-0 h-full">
                  <ContactsBlock
                    formData={formData}
                    setFormData={setFormData}
                    isEditing={isEditing}
                    phoneInputRef={phoneInputRef}
                    whatsappInputRef={whatsappInputRef}
                  />
                </TabsContent>

                <TabsContent value="organization" className="mt-0 h-full">
                  <OrganizationBlock
                    formData={formData}
                    setFormData={setFormData}
                    isEditing={isEditing}
                    onDaDataSearch={handleDaDataSearch}
                  />
                </TabsContent>

                <TabsContent value="legal" className="mt-0 h-full">
                  <LegalBlock formData={formData} setFormData={setFormData} isEditing={isEditing} />
                </TabsContent>

                {profileSettings.user?.organization?.type &&
                  ['FULFILLMENT', 'LOGIST', 'WHOLESALE', 'SELLER'].includes(profileSettings.user.organization.type) && (
                    <TabsContent value="financial" className="mt-0 h-full">
                      <FinancialBlock formData={formData} setFormData={setFormData} isEditing={isEditing} />
                    </TabsContent>
                  )}

                {profileSettings.user?.organization?.type === 'SELLER' && (
                  <TabsContent value="integrations" className="mt-0 h-full">
                    <IntegrationsBlock formData={formData} setFormData={setFormData} isEditing={isEditing} />
                  </TabsContent>
                )}

                {profileSettings.user?.organization?.type === 'WHOLESALE' && (
                  <TabsContent value="market" className="mt-0 h-full">
                    <MarketBlock formData={formData} setFormData={setFormData} isEditing={isEditing} />
                  </TabsContent>
                )}
              </div>
            </Tabs>
          </div>
        </div>
      </div>
    </div>
  )
}
