'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Settings,
  Building,
  Receipt,
  Bell,
  Bot,
  Wifi,
  Save,
  Loader2,
  CheckCircle,
  AlertTriangle,
  RefreshCw,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { api } from '@/lib/api'
import { useToast } from '@/hooks/use-toast'

// ---- Types ----
interface GeneralSettings {
  companyName: string
  address: string
  phone: string
  email: string
  logoUrl: string
}

interface BillingSettings {
  defaultTaxRate: number
  lateFee: number
  gracePeriod: number
  currency: string
  invoicePrefix: string
}

interface NotificationSettings {
  whatsappEnabled: boolean
  emailEnabled: boolean
  smsEnabled: boolean
  expiryReminderDays: number
  paymentReminderEnabled: boolean
}

interface AutomationSettings {
  autoExpire: boolean
  autoSuspend: boolean
  syncInterval: number
  lastSyncStatus: string
}

interface NetworkSettings {
  radiusServerIp: string
  radiusSecret: string
  mikrotikIp: string
  mikrotikApiPort: number
}

// ---- Default Settings ----
const defaultGeneral: GeneralSettings = {
  companyName: 'ISP Billing Pro',
  address: 'Dhaka, Bangladesh',
  phone: '+880 1700 000000',
  email: 'admin@ispbilling.com',
  logoUrl: '',
}

const defaultBilling: BillingSettings = {
  defaultTaxRate: 0,
  lateFee: 5,
  gracePeriod: 7,
  currency: 'BDT',
  invoicePrefix: 'INV',
}

const defaultNotifications: NotificationSettings = {
  whatsappEnabled: true,
  emailEnabled: true,
  smsEnabled: false,
  expiryReminderDays: 3,
  paymentReminderEnabled: true,
}

const defaultAutomation: AutomationSettings = {
  autoExpire: true,
  autoSuspend: true,
  syncInterval: 5,
  lastSyncStatus: 'Success - 2 minutes ago',
}

const defaultNetwork: NetworkSettings = {
  radiusServerIp: '192.168.1.1',
  radiusSecret: '',
  mikrotikIp: '192.168.1.1',
  mikrotikApiPort: 8728,
}

// ---- Skeleton ----
function FormSkeleton() {
  return (
    <div className="space-y-4">
      {Array.from({ length: 4 }).map((_, i) => (
        <div key={i} className="space-y-2">
          <Skeleton className="h-4 w-24" />
          <Skeleton className="h-10 w-full" />
        </div>
      ))}
    </div>
  )
}

// ---- Main Component ----
export default function SettingsView() {
  const { toast } = useToast()
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState<string | null>(null)

  // Settings state
  const [general, setGeneral] = useState<GeneralSettings>(defaultGeneral)
  const [billing, setBilling] = useState<BillingSettings>(defaultBilling)
  const [notifications, setNotifications] = useState<NotificationSettings>(defaultNotifications)
  const [automation, setAutomation] = useState<AutomationSettings>(defaultAutomation)
  const [network, setNetwork] = useState<NetworkSettings>(defaultNetwork)

  // Load settings
  const fetchSettings = useCallback(async () => {
    setLoading(true)
    try {
      const res = await api.get<Record<string, unknown>>('/api/settings')
      // If we get settings, use them; otherwise keep defaults
      if (res.success && res.data) {
        const data = res.data as Record<string, unknown>
        if (data.general) setGeneral(data.general as GeneralSettings)
        if (data.billing) setBilling(data.billing as BillingSettings)
        if (data.notifications) setNotifications(data.notifications as NotificationSettings)
        if (data.automation) setAutomation(data.automation as AutomationSettings)
        if (data.network) setNetwork(data.network as NetworkSettings)
      }
    } catch {
      // Keep defaults
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchSettings()
  }, [fetchSettings])

  // Save handler
  const handleSave = async (section: string, data: Record<string, unknown>) => {
    setSaving(section)
    try {
      const res = await api.put('/api/settings', data)
      if (res.success) {
        toast({
          title: 'Settings saved',
          description: `${section} settings have been updated successfully.`,
        })
      } else {
        toast({
          title: 'Save failed',
          description: res.error || 'Failed to save settings',
          variant: 'destructive',
        })
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Network error while saving settings',
        variant: 'destructive',
      })
    } finally {
      setSaving(null)
    }
  }

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Settings</h1>
          <p className="text-muted-foreground mt-1">
            Configure your ISP billing system preferences
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchSettings} disabled={loading}>
          <RefreshCw className={`size-4 ${loading ? 'animate-spin' : ''}`} />
          Reload
        </Button>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="general">
        <TabsList>
          <TabsTrigger value="general" className="gap-1.5">
            <Building className="size-3.5" />
            <span className="hidden sm:inline">General</span>
          </TabsTrigger>
          <TabsTrigger value="billing" className="gap-1.5">
            <Receipt className="size-3.5" />
            <span className="hidden sm:inline">Billing</span>
          </TabsTrigger>
          <TabsTrigger value="notifications" className="gap-1.5">
            <Bell className="size-3.5" />
            <span className="hidden sm:inline">Notifications</span>
          </TabsTrigger>
          <TabsTrigger value="automation" className="gap-1.5">
            <Bot className="size-3.5" />
            <span className="hidden sm:inline">Automation</span>
          </TabsTrigger>
          <TabsTrigger value="network" className="gap-1.5">
            <Wifi className="size-3.5" />
            <span className="hidden sm:inline">Network</span>
          </TabsTrigger>
        </TabsList>

        {/* ===== General Tab ===== */}
        <TabsContent value="general" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                <Building className="size-4" />
                Company Information
              </CardTitle>
              <CardDescription>Manage your company details and branding</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <FormSkeleton />
              ) : (
                <div className="space-y-4 max-w-2xl">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="companyName">Company Name</Label>
                      <Input
                        id="companyName"
                        value={general.companyName}
                        onChange={(e) => setGeneral({ ...general, companyName: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="email">Email</Label>
                      <Input
                        id="email"
                        type="email"
                        value={general.email}
                        onChange={(e) => setGeneral({ ...general, email: e.target.value })}
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="phone">Phone</Label>
                      <Input
                        id="phone"
                        value={general.phone}
                        onChange={(e) => setGeneral({ ...general, phone: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="logoUrl">Logo URL</Label>
                      <Input
                        id="logoUrl"
                        placeholder="https://example.com/logo.png"
                        value={general.logoUrl}
                        onChange={(e) => setGeneral({ ...general, logoUrl: e.target.value })}
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="address">Address</Label>
                    <Input
                      id="address"
                      value={general.address}
                      onChange={(e) => setGeneral({ ...general, address: e.target.value })}
                    />
                  </div>
                  <Separator />
                  <div className="flex justify-end">
                    <Button
                      onClick={() => handleSave('General', { general })}
                      disabled={saving === 'General'}
                    >
                      {saving === 'General' ? (
                        <Loader2 className="size-4 animate-spin" />
                      ) : (
                        <Save className="size-4" />
                      )}
                      Save Changes
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== Billing Tab ===== */}
        <TabsContent value="billing" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                <Receipt className="size-4" />
                Billing Configuration
              </CardTitle>
              <CardDescription>Set up tax rates, late fees, and invoice settings</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <FormSkeleton />
              ) : (
                <div className="space-y-4 max-w-2xl">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="taxRate">Default Tax Rate (%)</Label>
                      <Input
                        id="taxRate"
                        type="number"
                        min="0"
                        max="100"
                        value={billing.defaultTaxRate}
                        onChange={(e) => setBilling({ ...billing, defaultTaxRate: Number(e.target.value) })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="lateFee">Late Fee (%)</Label>
                      <Input
                        id="lateFee"
                        type="number"
                        min="0"
                        max="100"
                        value={billing.lateFee}
                        onChange={(e) => setBilling({ ...billing, lateFee: Number(e.target.value) })}
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="gracePeriod">Grace Period (days)</Label>
                      <Input
                        id="gracePeriod"
                        type="number"
                        min="0"
                        value={billing.gracePeriod}
                        onChange={(e) => setBilling({ ...billing, gracePeriod: Number(e.target.value) })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="currency">Currency</Label>
                      <Input
                        id="currency"
                        value={billing.currency}
                        disabled
                        className="bg-muted"
                      />
                      <p className="text-xs text-muted-foreground">Currency is fixed to BDT (৳)</p>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="invoicePrefix">Invoice Prefix</Label>
                    <Input
                      id="invoicePrefix"
                      value={billing.invoicePrefix}
                      onChange={(e) => setBilling({ ...billing, invoicePrefix: e.target.value })}
                    />
                  </div>
                  <Separator />
                  <div className="flex justify-end">
                    <Button
                      onClick={() => handleSave('Billing', { billing })}
                      disabled={saving === 'Billing'}
                    >
                      {saving === 'Billing' ? (
                        <Loader2 className="size-4 animate-spin" />
                      ) : (
                        <Save className="size-4" />
                      )}
                      Save Changes
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== Notifications Tab ===== */}
        <TabsContent value="notifications" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                <Bell className="size-4" />
                Notification Preferences
              </CardTitle>
              <CardDescription>Configure how and when notifications are sent</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <FormSkeleton />
              ) : (
                <div className="space-y-6 max-w-2xl">
                  {/* Toggle Settings */}
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label className="text-sm font-medium">WhatsApp Notifications</Label>
                        <p className="text-xs text-muted-foreground">Send notifications via WhatsApp</p>
                      </div>
                      <Switch
                        checked={notifications.whatsappEnabled}
                        onCheckedChange={(checked) => setNotifications({ ...notifications, whatsappEnabled: checked })}
                      />
                    </div>
                    <Separator />
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label className="text-sm font-medium">Email Notifications</Label>
                        <p className="text-xs text-muted-foreground">Send notifications via email</p>
                      </div>
                      <Switch
                        checked={notifications.emailEnabled}
                        onCheckedChange={(checked) => setNotifications({ ...notifications, emailEnabled: checked })}
                      />
                    </div>
                    <Separator />
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label className="text-sm font-medium">SMS Notifications</Label>
                        <p className="text-xs text-muted-foreground">Send notifications via SMS</p>
                      </div>
                      <Switch
                        checked={notifications.smsEnabled}
                        onCheckedChange={(checked) => setNotifications({ ...notifications, smsEnabled: checked })}
                      />
                    </div>
                    <Separator />
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label className="text-sm font-medium">Payment Reminders</Label>
                        <p className="text-xs text-muted-foreground">Send payment reminder notifications</p>
                      </div>
                      <Switch
                        checked={notifications.paymentReminderEnabled}
                        onCheckedChange={(checked) => setNotifications({ ...notifications, paymentReminderEnabled: checked })}
                      />
                    </div>
                  </div>

                  <Separator />

                  <div className="space-y-2">
                    <Label htmlFor="expiryDays">Expiry Reminder Days</Label>
                    <p className="text-xs text-muted-foreground">Send reminder before this many days of expiry</p>
                    <Input
                      id="expiryDays"
                      type="number"
                      min="0"
                      max="30"
                      value={notifications.expiryReminderDays}
                      onChange={(e) => setNotifications({ ...notifications, expiryReminderDays: Number(e.target.value) })}
                      className="w-32"
                    />
                  </div>

                  <Separator />

                  <div className="flex justify-end">
                    <Button
                      onClick={() => handleSave('Notifications', { notifications })}
                      disabled={saving === 'Notifications'}
                    >
                      {saving === 'Notifications' ? (
                        <Loader2 className="size-4 animate-spin" />
                      ) : (
                        <Save className="size-4" />
                      )}
                      Save Changes
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== Automation Tab ===== */}
        <TabsContent value="automation" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                <Bot className="size-4" />
                Automation Rules
              </CardTitle>
              <CardDescription>Configure automated actions and sync settings</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <FormSkeleton />
              ) : (
                <div className="space-y-6 max-w-2xl">
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label className="text-sm font-medium">Auto-Expire</Label>
                        <p className="text-xs text-muted-foreground">Automatically expire subscriptions on due date</p>
                      </div>
                      <Switch
                        checked={automation.autoExpire}
                        onCheckedChange={(checked) => setAutomation({ ...automation, autoExpire: checked })}
                      />
                    </div>
                    <Separator />
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label className="text-sm font-medium">Auto-Suspend</Label>
                        <p className="text-xs text-muted-foreground">Suspend accounts after grace period</p>
                      </div>
                      <Switch
                        checked={automation.autoSuspend}
                        onCheckedChange={(checked) => setAutomation({ ...automation, autoSuspend: checked })}
                      />
                    </div>
                  </div>

                  <Separator />

                  <div className="space-y-2">
                    <Label htmlFor="syncInterval">Sync Interval (minutes)</Label>
                    <p className="text-xs text-muted-foreground">How often to sync with network devices</p>
                    <Select
                      value={String(automation.syncInterval)}
                      onValueChange={(v) => setAutomation({ ...automation, syncInterval: Number(v) })}
                    >
                      <SelectTrigger className="w-40">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1">1 minute</SelectItem>
                        <SelectItem value="5">5 minutes</SelectItem>
                        <SelectItem value="10">10 minutes</SelectItem>
                        <SelectItem value="15">15 minutes</SelectItem>
                        <SelectItem value="30">30 minutes</SelectItem>
                        <SelectItem value="60">1 hour</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="flex items-center gap-2 p-3 rounded-lg bg-muted">
                    {automation.lastSyncStatus.startsWith('Success') ? (
                      <CheckCircle className="size-4 text-emerald-500 shrink-0" />
                    ) : (
                      <AlertTriangle className="size-4 text-amber-500 shrink-0" />
                    )}
                    <p className="text-xs text-muted-foreground">
                      Last sync: {automation.lastSyncStatus}
                    </p>
                  </div>

                  <Separator />

                  <div className="flex justify-end">
                    <Button
                      onClick={() => handleSave('Automation', { automation })}
                      disabled={saving === 'Automation'}
                    >
                      {saving === 'Automation' ? (
                        <Loader2 className="size-4 animate-spin" />
                      ) : (
                        <Save className="size-4" />
                      )}
                      Save Changes
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== Network Tab ===== */}
        <TabsContent value="network" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                <Wifi className="size-4" />
                Network Configuration
              </CardTitle>
              <CardDescription>RADIUS and MikroTik device settings</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <FormSkeleton />
              ) : (
                <div className="space-y-4 max-w-2xl">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="radiusIp">RADIUS Server IP</Label>
                      <Input
                        id="radiusIp"
                        placeholder="192.168.1.1"
                        value={network.radiusServerIp}
                        onChange={(e) => setNetwork({ ...network, radiusServerIp: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="radiusSecret">RADIUS Secret</Label>
                      <Input
                        id="radiusSecret"
                        type="password"
                        placeholder="Enter RADIUS secret"
                        value={network.radiusSecret}
                        onChange={(e) => setNetwork({ ...network, radiusSecret: e.target.value })}
                      />
                    </div>
                  </div>
                  <Separator />
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="mikrotikIp">MikroTik IP</Label>
                      <Input
                        id="mikrotikIp"
                        placeholder="192.168.1.1"
                        value={network.mikrotikIp}
                        onChange={(e) => setNetwork({ ...network, mikrotikIp: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="mikrotikPort">MikroTik API Port</Label>
                      <Input
                        id="mikrotikPort"
                        type="number"
                        min="1"
                        max="65535"
                        value={network.mikrotikApiPort}
                        onChange={(e) => setNetwork({ ...network, mikrotikApiPort: Number(e.target.value) })}
                      />
                    </div>
                  </div>

                  <div className="flex items-center gap-2 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-900/30">
                    <AlertTriangle className="size-4 text-amber-500 shrink-0" />
                    <p className="text-xs text-amber-700 dark:text-amber-400">
                      Changing network settings may disrupt active connections. Apply changes during maintenance windows.
                    </p>
                  </div>

                  <Separator />

                  <div className="flex justify-end">
                    <Button
                      onClick={() => handleSave('Network', { network })}
                      disabled={saving === 'Network'}
                    >
                      {saving === 'Network' ? (
                        <Loader2 className="size-4 animate-spin" />
                      ) : (
                        <Save className="size-4" />
                      )}
                      Save Changes
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
