'use client'

import { useEffect, useRef, useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Upload, X, Building2, Globe, CreditCard, Image as ImageIcon } from 'lucide-react'
import { api, type ApiResponse, type CompanySettings } from '@/lib/api'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Select } from '@/components/ui/Select'
import { Card } from '@/components/ui/Card'

function SectionHeader({ icon: Icon, title }: { icon: React.ElementType; title: string }) {
  return (
    <div className="mb-4 flex items-center gap-2 border-b border-[var(--premium-divider)] pb-3">
      <div className="premium-chip flex h-8 w-8 items-center justify-center rounded-xl">
        <Icon size={15} className="text-accent-600 dark:text-accent-400" />
      </div>
      <h3 className="text-sm font-semibold text-[var(--premium-text)]">{title}</h3>
    </div>
  )
}

export function SettingsPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [dragOver, setDragOver] = useState(false)

  const { data, isLoading } = useQuery({
    queryKey: ['company-settings'],
    queryFn: () => api.get<ApiResponse<CompanySettings>>('/company-settings'),
  })

  const settings = data?.data?.data

  const { register, handleSubmit } = useForm<CompanySettings>({
    values: settings,
  })

  const saveMutation = useMutation({
    mutationFn: (form: CompanySettings) => api.put('/company-settings', form),
    onSuccess: () => {
      toast.success(t('settings.saved'))
      queryClient.invalidateQueries({ queryKey: ['company-settings'] })
    },
    onError: () => toast.error(t('settings.saveFailed')),
  })

  const logoMutation = useMutation({
    mutationFn: (file: File) => {
      const fd = new FormData()
      fd.append('logo', file)
      return api.post('/company-settings/logo', fd, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
    },
    onSuccess: () => {
      toast.success(t('settings.logo.uploaded'))
      setPreview(null)
      queryClient.invalidateQueries({ queryKey: ['company-settings'] })
    },
    onError: () => toast.error(t('settings.logo.uploadFailed')),
  })

  const deleteLogoMutation = useMutation({
    mutationFn: () => api.delete('/company-settings/logo'),
    onSuccess: () => {
      toast.success(t('settings.logo.removed'))
      setPreview(null)
      queryClient.invalidateQueries({ queryKey: ['company-settings'] })
    },
    onError: () => toast.error(t('settings.logo.removeFailed')),
  })

  const handleFileSelect = (file: File) => {
    const allowed = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
    if (!allowed.includes(file.type)) {
      toast.error(t('settings.logo.invalidType'))
      return
    }
    if (file.size > 2 * 1024 * 1024) {
      toast.error(t('settings.logo.tooLarge'))
      return
    }
    const reader = new FileReader()
    reader.onload = (e) => setPreview(e.target?.result as string)
    reader.readAsDataURL(file)
    logoMutation.mutate(file)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    const file = e.dataTransfer.files[0]
    if (file) handleFileSelect(file)
  }

  // Load logo via authenticated API (not public /uploads)
  const [authLogoUrl, setAuthLogoUrl] = useState<string | null>(null)
  useEffect(() => {
    let objectUrl: string | null = null
    let cancelled = false
    async function loadLogo() {
      if (!settings?.has_logo && !settings?.logo_url) {
        setAuthLogoUrl(null)
        return
      }
      try {
        const res = await api.get('/company-settings/logo/file', { responseType: 'blob' })
        if (cancelled) return
        objectUrl = URL.createObjectURL(res.data)
        setAuthLogoUrl(objectUrl)
      } catch {
        if (!cancelled) setAuthLogoUrl(null)
      }
    }
    loadLogo()
    return () => {
      cancelled = true
      if (objectUrl) URL.revokeObjectURL(objectUrl)
    }
  }, [settings?.has_logo, settings?.logo_url, settings?.id])

  const currentLogo = preview || authLogoUrl

  if (isLoading) return (
    <div className="flex h-40 items-center justify-center">
      <div className="h-8 w-8 animate-spin rounded-full border-2 border-brand-500 border-t-transparent" />
    </div>
  )

  return (
    <div className="mx-auto max-w-2xl space-y-5">
      <h1 className="premium-heading animate-fade-in-up text-2xl font-bold">{t('settings.title')}</h1>

      {/* ── LOGO SECTION ── */}
      <div className="animate-fade-in-up stagger-1">
        <Card elevated>
          <SectionHeader icon={ImageIcon} title={t('settings.sections.logo')} />

          <div className="flex flex-col items-start gap-5 sm:flex-row sm:items-center">
            {/* Logo preview */}
            <div
              className="premium-chip depth-showroom relative flex h-28 w-28 shrink-0 items-center justify-center overflow-hidden rounded-2xl border-2 border-dashed border-[var(--premium-border)] transition-colors"
              style={currentLogo ? { borderStyle: 'solid', borderColor: 'rgba(61,139,110,0.4)' } : {}}
            >
              {currentLogo ? (
                <>
                  <img
                    src={currentLogo}
                    alt={t('settings.sections.logo')}
                    className="h-full w-full object-contain p-2"
                  />
                  <button
                    type="button"
                    onClick={() => deleteLogoMutation.mutate()}
                    disabled={deleteLogoMutation.isPending}
                    className="absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-red-500/80 text-white hover:bg-red-600 transition-colors"
                    title={t('settings.logo.removeLogo')}
                  >
                    <X size={11} />
                  </button>
                </>
              ) : (
                <div className="flex flex-col items-center gap-1 text-center">
                  <ImageIcon size={24} className="text-[var(--text-muted)] opacity-40" />
                  <span className="text-[10px] text-[var(--text-muted)] opacity-60">{t('settings.logo.noLogo')}</span>
                </div>
              )}
            </div>

            {/* Upload area */}
            <div
              className={`flex flex-1 flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed p-5 text-center transition-colors ${
                dragOver
                  ? 'border-brand-500 bg-[var(--premium-hover-bg)]'
                  : 'border-[var(--premium-border)] hover:border-brand-400/50 hover:bg-[var(--premium-hover-bg)]'
              }`}
              onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
              onDragLeave={() => setDragOver(false)}
              onDrop={handleDrop}
            >
              <Upload size={20} className="text-brand-500" />
              <div>
                <p className="text-sm font-semibold text-[var(--premium-text)]">
                  {t('settings.logo.dragDrop')}{' '}
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className="text-brand-500 underline-offset-2 hover:underline"
                  >
                    {t('settings.logo.browse')}
                  </button>
                </p>
                <p className="mt-0.5 text-xs text-[var(--text-muted)]">{t('settings.logo.fileTypes')}</p>
              </div>
              {logoMutation.isPending && (
                <p className="text-xs text-brand-400">{t('settings.logo.uploading')}</p>
              )}
            </div>

            <input
              ref={fileInputRef}
              type="file"
              accept="image/jpeg,image/jpg,image/png,image/webp"
              className="hidden"
              onChange={(e) => {
                const file = e.target.files?.[0]
                if (file) handleFileSelect(file)
                e.target.value = ''
              }}
            />
          </div>
        </Card>
      </div>

      {/* ── SETTINGS FORM ── */}
      <form onSubmit={handleSubmit((form) => saveMutation.mutate(form))} className="space-y-5">

        {/* Company Information */}
        <div className="animate-fade-in-up stagger-2">
          <Card elevated>
            <SectionHeader icon={Building2} title={t('settings.sections.companyInfo')} />
            <div className="grid gap-4 sm:grid-cols-2">
              <Input label={t('settings.companyName')} {...register('company_name', { required: true })} />
              <Input label={t('settings.taxId')} {...register('tax_id')} />
              <Input label={t('settings.email')} type="email" {...register('email')} />
              <Input label={t('settings.phone')} type="tel" {...register('phone')} />
              <Input label={t('settings.website')} type="url" {...register('website')} />
              <Input label={t('settings.address')} {...register('address')} className="sm:col-span-2" />
            </div>
          </Card>
        </div>

        {/* Locale & Currency */}
        <div className="animate-fade-in-up stagger-3">
          <Card elevated>
            <SectionHeader icon={Globe} title={t('settings.sections.localeCurrency')} />
            <div className="grid gap-4 sm:grid-cols-2">
              <Input
                label={t('settings.currency')}
                {...register('default_currency')}
                placeholder={t('settings.placeholders.currency')}
                maxLength={3}
              />
              <Select
                label={t('settings.language')}
                {...register('default_language')}
                options={[
                  { value: 'en', label: t('settings.languages.en') },
                  { value: 'sq', label: t('settings.languages.sq') },
                  { value: 'it', label: t('settings.languages.it') },
                ]}
              />
              <Input
                label={t('settings.timezone')}
                {...register('timezone')}
                placeholder={t('settings.placeholders.timezone')}
              />
            </div>
          </Card>
        </div>

        {/* Banking */}
        <div className="animate-fade-in-up stagger-4">
          <Card elevated>
            <SectionHeader icon={CreditCard} title={t('settings.sections.banking')} />
            <div className="grid gap-4 sm:grid-cols-2">
              <Input
                label={t('settings.iban')}
                {...register('iban')}
                placeholder={t('settings.placeholders.iban')}
                className="sm:col-span-2"
              />
            </div>
          </Card>
        </div>

        <div className="animate-fade-in-up stagger-5 flex justify-end pb-4">
          <Button type="submit" disabled={saveMutation.isPending}>
            {saveMutation.isPending ? t('common.saving') : t('settings.saveSettings')}
          </Button>
        </div>
      </form>
    </div>
  )
}
