import { useState, useRef, useEffect } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { queryOptions } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import { useAuthStore } from '@/stores/auth.store'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { moduleListOptions, moduleMutations, moduleKeys } from '@/api/modules'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Save, Plus, Trash2, MapPin, Building, ImageIcon, Blocks, Lock, Settings2, Receipt, ShieldCheck } from 'lucide-react'
import { OVERRIDE_ACTIONS, getRequiredOverrides, setRequiredOverrides, getDiscountThreshold, setDiscountThreshold, type OverrideAction } from '@/components/pos/pos-manager-override'
import { toast } from 'sonner'

interface StoreSettings {
  id: string
  name: string
  phone: string | null
  email: string | null
  address: { street?: string; city?: string; state?: string; zip?: string } | null
  timezone: string
  logoFileId: string | null
  notes: string | null
}

interface Location {
  id: string
  name: string
  phone: string | null
  email: string | null
  address: { street?: string; city?: string; state?: string; zip?: string } | null
  timezone: string | null
  isActive: boolean
}

function storeOptions() {
  return queryOptions({
    queryKey: ['store'],
    queryFn: () => api.get<StoreSettings>('/v1/store'),
  })
}

function locationsOptions() {
  return queryOptions({
    queryKey: ['locations'],
    queryFn: () => api.get<{ data: Location[] }>('/v1/locations'),
  })
}

export const Route = createFileRoute('/_authenticated/settings')({
  component: SettingsPage,
})

function SettingsPage() {
  const queryClient = useQueryClient()
  const { data: store, isLoading } = useQuery(storeOptions())
  const { data: locationsData } = useQuery(locationsOptions())
  const [addLocationOpen, setAddLocationOpen] = useState(false)

  // Store edit state
  const [editing, setEditing] = useState(false)
  const [fields, setFields] = useState<Record<string, string>>({})

  const updateMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => api.patch<StoreSettings>('/v1/store', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['store'] })
      toast.success('Store settings updated')
      setEditing(false)
    },
    onError: (err) => toast.error(err.message),
  })

  function startEdit() {
    if (!store) return
    setFields({
      name: store.name,
      phone: store.phone ?? '',
      email: store.email ?? '',
      street: store.address?.street ?? '',
      city: store.address?.city ?? '',
      state: store.address?.state ?? '',
      zip: store.address?.zip ?? '',
      timezone: store.timezone,
      notes: store.notes ?? '',
    })
    setEditing(true)
  }

  function saveEdit() {
    updateMutation.mutate({
      name: fields.name,
      phone: fields.phone || null,
      email: fields.email || null,
      address: { street: fields.street, city: fields.city, state: fields.state, zip: fields.zip },
      timezone: fields.timezone,
      notes: fields.notes || null,
    })
  }

  if (isLoading) {
    return <div className="space-y-4 max-w-3xl"><Skeleton className="h-8 w-48" /><Skeleton className="h-64 w-full" /></div>
  }

  if (!store) {
    return <p className="text-muted-foreground">No store configured</p>
  }

  const locations = locationsData?.data ?? []

  return (
    <div className="space-y-6 max-w-3xl">
      <h1 className="text-2xl font-bold">Settings</h1>

      <Tabs defaultValue="store">
        <TabsList>
          <TabsTrigger value="store">Store</TabsTrigger>
          <TabsTrigger value="locations">Locations</TabsTrigger>
          <TabsTrigger value="modules">Modules</TabsTrigger>
          <TabsTrigger value="receipt">Receipt</TabsTrigger>
          <TabsTrigger value="pos">POS Security</TabsTrigger>
          <TabsTrigger value="advanced">Advanced</TabsTrigger>
        </TabsList>

        <TabsContent value="store" className="mt-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-lg flex items-center gap-2">
                <Building className="h-5 w-5" />Store Information
              </CardTitle>
              {!editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
              {editing && (
                <div className="flex gap-2">
                  <Button size="sm" onClick={saveEdit} disabled={updateMutation.isPending}>
                    <Save className="mr-1 h-3 w-3" />{updateMutation.isPending ? 'Saving...' : 'Save'}
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
                </div>
              )}
            </CardHeader>
            <CardContent className="space-y-6">
              <div>
                <LogoUpload entityId={store.id} category="logo" label="Store Logo" description="Used on PDFs, sidebar, and login screen" />
              </div>

              {editing ? (
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Store Name *</Label>
                      <Input value={fields.name} onChange={(e) => setFields((p) => ({ ...p, name: e.target.value }))} />
                    </div>
                    <div className="space-y-2">
                      <Label>Timezone</Label>
                      <Input value={fields.timezone} onChange={(e) => setFields((p) => ({ ...p, timezone: e.target.value }))} placeholder="America/Chicago" />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Phone</Label>
                      <Input value={fields.phone} onChange={(e) => setFields((p) => ({ ...p, phone: e.target.value }))} />
                    </div>
                    <div className="space-y-2">
                      <Label>Email</Label>
                      <Input value={fields.email} onChange={(e) => setFields((p) => ({ ...p, email: e.target.value }))} />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Street</Label>
                      <Input value={fields.street} onChange={(e) => setFields((p) => ({ ...p, street: e.target.value }))} />
                    </div>
                    <div className="grid grid-cols-3 gap-2">
                      <div className="space-y-2">
                        <Label>City</Label>
                        <Input value={fields.city} onChange={(e) => setFields((p) => ({ ...p, city: e.target.value }))} />
                      </div>
                      <div className="space-y-2">
                        <Label>State</Label>
                        <Input value={fields.state} onChange={(e) => setFields((p) => ({ ...p, state: e.target.value }))} />
                      </div>
                      <div className="space-y-2">
                        <Label>ZIP</Label>
                        <Input value={fields.zip} onChange={(e) => setFields((p) => ({ ...p, zip: e.target.value }))} />
                      </div>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>Notes</Label>
                    <Textarea value={fields.notes} onChange={(e) => setFields((p) => ({ ...p, notes: e.target.value }))} rows={2} />
                  </div>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2 text-sm">
                      <div className="text-lg font-semibold">{store.name}</div>
                      <div><span className="text-muted-foreground">Phone:</span> {store.phone ?? '-'}</div>
                      <div><span className="text-muted-foreground">Email:</span> {store.email ?? '-'}</div>
                      <div><span className="text-muted-foreground">Timezone:</span> {store.timezone}</div>
                    </div>
                    <div className="space-y-2 text-sm">
                      {store.address && (store.address.street || store.address.city) ? (
                        <>
                          <div className="font-medium flex items-center gap-1"><MapPin className="h-3 w-3" />Address</div>
                          {store.address.street && <div>{store.address.street}</div>}
                          <div>{[store.address.city, store.address.state, store.address.zip].filter(Boolean).join(', ')}</div>
                        </>
                      ) : (
                        <div className="text-muted-foreground">No address set</div>
                      )}
                      {store.notes && <div className="mt-2"><span className="text-muted-foreground">Notes:</span> {store.notes}</div>}
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="locations" className="mt-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-lg flex items-center gap-2">
                <MapPin className="h-5 w-5" />Locations
              </CardTitle>
              <AddLocationDialog open={addLocationOpen} onOpenChange={setAddLocationOpen} />
            </CardHeader>
            <CardContent>
              {locations.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">No locations yet — add your first store location</p>
              ) : (
                <div className="space-y-3">
                  {locations.map((loc) => (
                    <LocationCard key={loc.id} location={loc} />
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="modules" className="mt-4">
          <ModulesCard />
        </TabsContent>

        <TabsContent value="receipt" className="mt-4">
          <ReceiptSettingsCard />
        </TabsContent>

        <TabsContent value="pos" className="mt-4">
          <ManagerOverridesCard />
        </TabsContent>

        <TabsContent value="advanced" className="mt-4">
          <AppConfigCard />
        </TabsContent>
      </Tabs>
    </div>
  )
}

function ModulesCard() {
  const queryClient = useQueryClient()
  const hasPermission = useAuthStore((s) => s.hasPermission)
  const canEdit = hasPermission('settings.edit')

  const { data: modulesData, isLoading } = useQuery(moduleListOptions())
  const modules = modulesData?.data ?? []

  const toggleMutation = useMutation({
    mutationFn: ({ slug, enabled }: { slug: string; enabled: boolean }) => moduleMutations.toggle(slug, enabled),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: moduleKeys.list })
      toast.success('Module updated')
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg flex items-center gap-2">
          <Blocks className="h-5 w-5" />Modules
        </CardTitle>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="space-y-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-12 w-full" />)}</div>
        ) : (
          <div className="space-y-2">
            {modules.map((mod) => (
              <div key={mod.id} className="flex items-center justify-between p-3 rounded-md border">
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-sm">{mod.name}</span>
                    {!mod.licensed && (
                      <Badge variant="outline" className="text-[10px] gap-1">
                        <Lock className="h-2.5 w-2.5" />Not Licensed
                      </Badge>
                    )}
                  </div>
                  {mod.description && <p className="text-xs text-muted-foreground mt-0.5">{mod.description}</p>}
                </div>
                <Switch
                  checked={mod.enabled}
                  onCheckedChange={(checked) => toggleMutation.mutate({ slug: mod.slug, enabled: checked })}
                  disabled={!canEdit || !mod.licensed || toggleMutation.isPending}
                />
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

interface AppConfigEntry {
  key: string
  value: string | null
  description: string | null
  updatedAt: string
}

const LOG_LEVELS = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const

function configOptions() {
  return queryOptions({
    queryKey: ['config'],
    queryFn: () => api.get<{ data: AppConfigEntry[] }>('/v1/config'),
  })
}

function AppConfigCard() {
  const queryClient = useQueryClient()
  const hasPermission = useAuthStore((s) => s.hasPermission)
  const canEdit = hasPermission('settings.edit')

  const { data: configData, isLoading } = useQuery(configOptions())
  const configs = configData?.data ?? []
  const logLevel = configs.find((c) => c.key === 'log_level')?.value ?? 'info'

  const updateMutation = useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) =>
      api.patch<AppConfigEntry>(`/v1/config/${key}`, { value }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['config'] })
      toast.success('Configuration updated')
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg flex items-center gap-2">
          <Settings2 className="h-5 w-5" />App Configuration
        </CardTitle>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-12 w-full" />
        ) : (
          <div className="space-y-4">
            <div className="flex items-center justify-between p-3 rounded-md border">
              <div className="min-w-0">
                <span className="font-medium text-sm">Log Level</span>
                <p className="text-xs text-muted-foreground mt-0.5">Controls the verbosity of application logs</p>
              </div>
              <Select
                value={logLevel}
                onValueChange={(value) => updateMutation.mutate({ key: 'log_level', value })}
                disabled={!canEdit || updateMutation.isPending}
              >
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {LOG_LEVELS.map((level) => (
                    <SelectItem key={level} value={level}>
                      {level}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

const RECEIPT_FIELDS = [
  { key: 'receipt_header', label: 'Header Text', placeholder: "e.g. San Antonio's Premier String Shop", multiline: false },
  { key: 'receipt_footer', label: 'Footer Message', placeholder: 'e.g. Thank you for your business!', multiline: false },
  { key: 'receipt_return_policy', label: 'Return Policy', placeholder: 'e.g. Returns accepted within 30 days with receipt.', multiline: true },
  { key: 'receipt_social', label: 'Website / Social', placeholder: 'e.g. www.demostore.com | @demostore', multiline: false },
]

function ReceiptSettingsCard() {
  const queryClient = useQueryClient()
  const hasPermission = useAuthStore((s) => s.hasPermission)
  const canEdit = hasPermission('settings.edit')

  const { data: configData, isLoading } = useQuery(configOptions())
  const configs = configData?.data ?? []

  const [editing, setEditing] = useState(false)
  const [fields, setFields] = useState<Record<string, string>>({})

  function startEdit() {
    const f: Record<string, string> = {}
    for (const rf of RECEIPT_FIELDS) {
      f[rf.key] = configs.find((c) => c.key === rf.key)?.value ?? ''
    }
    setFields(f)
    setEditing(true)
  }

  const saveMutation = useMutation({
    mutationFn: async () => {
      for (const rf of RECEIPT_FIELDS) {
        await api.patch(`/v1/config/${rf.key}`, { value: fields[rf.key] || '' })
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['config'] })
      toast.success('Receipt settings saved')
      setEditing(false)
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="text-lg flex items-center gap-2">
          <Receipt className="h-5 w-5" />Receipt Customization
        </CardTitle>
        {canEdit && !editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
        {editing && (
          <div className="flex gap-2">
            <Button size="sm" onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
              <Save className="mr-1 h-3 w-3" />{saveMutation.isPending ? 'Saving...' : 'Save'}
            </Button>
            <Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
          </div>
        )}
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-32 w-full" />
        ) : editing ? (
          <div className="space-y-4">
            {RECEIPT_FIELDS.map((rf) => (
              <div key={rf.key} className="space-y-2">
                <Label>{rf.label}</Label>
                {rf.multiline ? (
                  <Textarea
                    value={fields[rf.key] ?? ''}
                    onChange={(e) => setFields((p) => ({ ...p, [rf.key]: e.target.value }))}
                    placeholder={rf.placeholder}
                    rows={2}
                  />
                ) : (
                  <Input
                    value={fields[rf.key] ?? ''}
                    onChange={(e) => setFields((p) => ({ ...p, [rf.key]: e.target.value }))}
                    placeholder={rf.placeholder}
                  />
                )}
              </div>
            ))}
          </div>
        ) : (
          <div className="space-y-3">
            {RECEIPT_FIELDS.map((rf) => {
              const value = configs.find((c) => c.key === rf.key)?.value
              return (
                <div key={rf.key} className="flex justify-between items-start">
                  <span className="text-sm text-muted-foreground">{rf.label}</span>
                  <span className="text-sm text-right max-w-[60%]">{value || <span className="text-muted-foreground/50">Not set</span>}</span>
                </div>
              )
            })}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

function ManagerOverridesCard() {
  const [overrides, setOverrides] = useState<Set<OverrideAction>>(() => getRequiredOverrides())
  const [threshold, setThreshold] = useState(() => getDiscountThreshold())

  function toggle(action: OverrideAction) {
    setOverrides((prev) => {
      const next = new Set(prev)
      if (next.has(action)) next.delete(action)
      else next.add(action)
      setRequiredOverrides(next)
      return next
    })
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg flex items-center gap-2">
          <ShieldCheck className="h-5 w-5" />Manager Overrides
        </CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-sm text-muted-foreground mb-4">
          When enabled, these actions will require a manager or admin to enter their PIN before proceeding. This setting is stored per device.
        </p>
        <div className="space-y-2">
          {OVERRIDE_ACTIONS.map((action) => (
            <div key={action.key} className="flex items-center justify-between p-3 rounded-md border">
              <div className="min-w-0">
                <span className="font-medium text-sm">{action.label}</span>
                <p className="text-xs text-muted-foreground mt-0.5">{action.description}</p>
              </div>
              <Switch
                checked={overrides.has(action.key)}
                onCheckedChange={() => toggle(action.key)}
              />
            </div>
          ))}
        </div>

        <div className="mt-4 p-3 rounded-md border">
          <div className="flex items-center justify-between">
            <div className="min-w-0">
              <span className="font-medium text-sm">Discount Threshold</span>
              <p className="text-xs text-muted-foreground mt-0.5">Require manager approval for discounts at or above this percentage. Set to 0 to disable.</p>
            </div>
            <div className="flex items-center gap-1">
              <Input
                type="number"
                min="0"
                max="100"
                className="w-20 h-8 text-sm text-right"
                value={threshold}
                onChange={(e) => {
                  const v = parseInt(e.target.value) || 0
                  setThreshold(v)
                  setDiscountThreshold(v)
                }}
              />
              <span className="text-sm text-muted-foreground">%</span>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

function LocationCard({ location }: { location: Location }) {
  const queryClient = useQueryClient()
  const [editing, setEditing] = useState(false)
  const [fields, setFields] = useState<Record<string, string>>({})

  const updateMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => api.patch<Location>(`/v1/locations/${location.id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] })
      toast.success('Location updated')
      setEditing(false)
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteMutation = useMutation({
    mutationFn: () => api.del(`/v1/locations/${location.id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] })
      toast.success('Location removed')
    },
    onError: (err) => toast.error(err.message),
  })

  function startEdit() {
    setFields({
      name: location.name,
      phone: location.phone ?? '',
      email: location.email ?? '',
      street: location.address?.street ?? '',
      city: location.address?.city ?? '',
      state: location.address?.state ?? '',
      zip: location.address?.zip ?? '',
    })
    setEditing(true)
  }

  function saveEdit() {
    updateMutation.mutate({
      name: fields.name,
      phone: fields.phone || null,
      email: fields.email || null,
      address: { street: fields.street, city: fields.city, state: fields.state, zip: fields.zip },
    })
  }

  if (editing) {
    return (
      <div className="rounded-md border p-4 space-y-3">
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1"><Label className="text-xs">Name</Label><Input className="h-8" value={fields.name} onChange={(e) => setFields((p) => ({ ...p, name: e.target.value }))} /></div>
          <div className="space-y-1"><Label className="text-xs">Phone</Label><Input className="h-8" value={fields.phone} onChange={(e) => setFields((p) => ({ ...p, phone: e.target.value }))} /></div>
        </div>
        <div className="space-y-1"><Label className="text-xs">Email</Label><Input className="h-8" value={fields.email} onChange={(e) => setFields((p) => ({ ...p, email: e.target.value }))} /></div>
        <div className="grid grid-cols-4 gap-2">
          <div className="col-span-2 space-y-1"><Label className="text-xs">Street</Label><Input className="h-8" value={fields.street} onChange={(e) => setFields((p) => ({ ...p, street: e.target.value }))} /></div>
          <div className="space-y-1"><Label className="text-xs">City</Label><Input className="h-8" value={fields.city} onChange={(e) => setFields((p) => ({ ...p, city: e.target.value }))} /></div>
          <div className="grid grid-cols-2 gap-1">
            <div className="space-y-1"><Label className="text-xs">State</Label><Input className="h-8" value={fields.state} onChange={(e) => setFields((p) => ({ ...p, state: e.target.value }))} /></div>
            <div className="space-y-1"><Label className="text-xs">ZIP</Label><Input className="h-8" value={fields.zip} onChange={(e) => setFields((p) => ({ ...p, zip: e.target.value }))} /></div>
          </div>
        </div>
        <div className="flex gap-2">
          <Button size="sm" onClick={saveEdit} disabled={updateMutation.isPending}>{updateMutation.isPending ? 'Saving...' : 'Save'}</Button>
          <Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
        </div>
      </div>
    )
  }

  return (
    <div className="flex items-center justify-between p-3 rounded-md border">
      <div>
        <p className="font-medium">{location.name}</p>
        <div className="flex gap-3 text-sm text-muted-foreground">
          {location.phone && <span>{location.phone}</span>}
          {location.address?.city && <span>{location.address.city}{location.address.state ? `, ${location.address.state}` : ''}</span>}
        </div>
      </div>
      <div className="flex gap-1">
        <Button variant="ghost" size="sm" onClick={startEdit}>Edit</Button>
        <Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate()}>
          <Trash2 className="h-4 w-4 text-destructive" />
        </Button>
      </div>
    </div>
  )
}

function AddLocationDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
  const queryClient = useQueryClient()
  const [name, setName] = useState('')
  const [phone, setPhone] = useState('')
  const [email, setEmail] = useState('')
  const [street, setStreet] = useState('')
  const [city, setCity] = useState('')
  const [state, setState] = useState('')
  const [zip, setZip] = useState('')

  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => api.post<Location>('/v1/locations', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] })
      toast.success('Location added')
      onOpenChange(false)
      setName(''); setPhone(''); setEmail(''); setStreet(''); setCity(''); setState(''); setZip('')
    },
    onError: (err) => toast.error(err.message),
  })

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    mutation.mutate({
      name, phone: phone || undefined, email: email || undefined,
      address: { street, city, state, zip },
    })
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogTrigger asChild>
        <Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Location</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader><DialogTitle>Add Location</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2"><Label>Name *</Label><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Main Store, Downtown" required /></div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2"><Label>Phone</Label><Input value={phone} onChange={(e) => setPhone(e.target.value)} /></div>
            <div className="space-y-2"><Label>Email</Label><Input value={email} onChange={(e) => setEmail(e.target.value)} /></div>
          </div>
          <div className="space-y-2"><Label>Street</Label><Input value={street} onChange={(e) => setStreet(e.target.value)} /></div>
          <div className="grid grid-cols-3 gap-2">
            <div className="space-y-2"><Label>City</Label><Input value={city} onChange={(e) => setCity(e.target.value)} /></div>
            <div className="space-y-2"><Label>State</Label><Input value={state} onChange={(e) => setState(e.target.value)} /></div>
            <div className="space-y-2"><Label>ZIP</Label><Input value={zip} onChange={(e) => setZip(e.target.value)} /></div>
          </div>
          <Button type="submit" disabled={mutation.isPending}>{mutation.isPending ? 'Adding...' : 'Add Location'}</Button>
        </form>
      </DialogContent>
    </Dialog>
  )
}

function LogoUpload({ entityId, category, label, description }: { entityId: string; category: string; label: string; description: string }) {
  const queryClient = useQueryClient()
  const token = useAuthStore((s) => s.token)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [imgSrc, setImgSrc] = useState<string | null>(null)

  const { data: filesData } = useQuery(queryOptions({
    queryKey: ['files', 'company', entityId],
    queryFn: () => api.get<{ data: { id: string; path: string; filename: string }[] }>('/v1/files', { entityType: 'company', entityId }),
    enabled: !!entityId,
  }))

  const logoFile = filesData?.data?.find((f) => f.path.includes(`/${category}-`))

  // Load image via authenticated fetch
  useEffect(() => {
    if (!logoFile || !token) { setImgSrc(null); return }
    let cancelled = false
    let blobUrl: string | null = null
    async function load() {
      try {
        const res = await fetch(`/v1/files/serve/${logoFile!.path}`, {
          headers: { Authorization: `Bearer ${token}` },
        })
        if (!res.ok || cancelled) return
        const blob = await res.blob()
        if (!cancelled) { blobUrl = URL.createObjectURL(blob); setImgSrc(blobUrl) }
      } catch { /* ignore */ }
    }
    load()
    return () => { cancelled = true; if (blobUrl) URL.revokeObjectURL(blobUrl) }
  }, [logoFile?.path, token])

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return
    setUploading(true)
    try {
      if (logoFile) await api.del(`/v1/files/${logoFile.id}`)
      const formData = new FormData()
      formData.append('file', file)
      formData.append('entityType', 'company')
      formData.append('entityId', entityId)
      formData.append('category', category)
      const res = await fetch('/v1/files', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: formData })
      if (!res.ok) throw new Error('Upload failed')
      queryClient.invalidateQueries({ queryKey: ['files', 'company', entityId] })
      toast.success(`${label} updated`)
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Upload failed')
    } finally {
      setUploading(false)
      e.target.value = ''
    }
  }

  return (
    <div className="space-y-2">
      <Label className="text-xs text-muted-foreground">{label}</Label>
      <button
        type="button"
        onClick={() => fileInputRef.current?.click()}
        disabled={uploading}
        className="flex items-center justify-center w-64 h-32 rounded-lg border-2 border-dashed border-muted-foreground/30 bg-muted/30 hover:border-primary hover:bg-muted/50 transition-colors overflow-hidden"
      >
        {imgSrc ? (
          <img src={imgSrc} alt={label} className="max-w-full max-h-full object-contain p-2" />
        ) : (
          <div className="flex flex-col items-center gap-1 text-muted-foreground">
            <ImageIcon className="h-8 w-8" />
            <span className="text-xs">Click to upload</span>
          </div>
        )}
      </button>
      <p className="text-[10px] text-muted-foreground">{description}</p>
      <input ref={fileInputRef} type="file" accept="image/jpeg,image/png,image/webp,image/svg+xml" className="hidden" onChange={handleUpload} />
    </div>
  )
}
