"use client"

import { useState, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { sanitizeInput } from "@/lib/security/sanitize"
import { Mail, CreditCard, Percent, Wallet, Eye, EyeOff, Save, CheckCircle2, AlertCircle, Send } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Switch } from "@/components/ui/switch"
import { Badge } from "@/components/ui/badge"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"
import {
  smtpSettingsSchema,
  cashfreeSettingsSchema,
  agentCommissionSchema,
  withdrawSettingsSchema,
  type SMTPSettingsInput,
  type CashfreeSettingsInput,
  type AgentCommissionInput,
  type WithdrawSettingsInput,
} from "@/lib/validations/settings"
import { settingsDataStore, type AdminSettings, type WithdrawMethod } from "@/lib/data/settings"

export function AdminSettingsClient() {
  const [settings, setSettings] = useState<AdminSettings | null>(null)
  const [activeTab, setActiveTab] = useState("smtp")
  const [showSecrets, setShowSecrets] = useState<Record<string, boolean>>({})
  const toast = useToastEnhanced()

  useEffect(() => {
    setSettings(settingsDataStore.getSettings())
  }, [])

  const toggleSecret = (key: string) => {
    setShowSecrets((prev) => ({ ...prev, [key]: !prev[key] }))
  }

  // SMTP Form
  const smtpForm = useForm<SMTPSettingsInput>({
    resolver: zodResolver(smtpSettingsSchema),
    values: settings?.smtp,
  })

  // Cashfree Form
  const cashfreeForm = useForm<CashfreeSettingsInput>({
    resolver: zodResolver(cashfreeSettingsSchema),
    values: settings?.cashfree,
  })

  // Commission Form
  const commissionForm = useForm<AgentCommissionInput>({
    resolver: zodResolver(agentCommissionSchema),
    values: settings?.agentCommission,
  })

  // Withdraw Form
  const withdrawForm = useForm<WithdrawSettingsInput>({
    resolver: zodResolver(withdrawSettingsSchema),
    values: settings?.withdraw,
  })

  const onSMTPSubmit = (data: SMTPSettingsInput) => {
    const sanitized = {
      host: sanitizeInput(data.host),
      port: data.port,
      username: sanitizeInput(data.username),
      password: data.password,
      encryption: data.encryption,
      fromEmail: sanitizeInput(data.fromEmail),
      fromName: sanitizeInput(data.fromName),
    }
    settingsDataStore.updateSMTP(sanitized)
    setSettings(settingsDataStore.getSettings())
    toast.success({ title: "SMTP settings saved", description: "Your email configuration has been updated." })
  }

  const onCashfreeSubmit = (data: CashfreeSettingsInput) => {
    settingsDataStore.updateCashfree(data)
    setSettings(settingsDataStore.getSettings())
    toast.success({ title: "Payment gateway saved", description: "Cashfree settings have been updated." })
  }

  const onCommissionSubmit = (data: AgentCommissionInput) => {
    settingsDataStore.updateAgentCommission(data)
    setSettings(settingsDataStore.getSettings())
    toast.success({ title: "Commission settings saved", description: "Agent commission configuration updated." })
  }

  const onWithdrawSubmit = (data: WithdrawSettingsInput) => {
    settingsDataStore.updateWithdraw(data)
    setSettings(settingsDataStore.getSettings())
    toast.success({ title: "Withdraw settings saved", description: "Withdrawal configuration updated." })
  }

  const toggleWithdrawMethod = (method: WithdrawMethod) => {
    settingsDataStore.updateWithdrawMethod(method.id, { isActive: !method.isActive })
    setSettings(settingsDataStore.getSettings())
    toast.info({
      title: method.isActive ? "Method disabled" : "Method enabled",
      description: `${method.name} has been ${method.isActive ? "disabled" : "enabled"}.`,
    })
  }

  if (!settings) {
    return (
      <div className="admin-section">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="animate-pulse text-muted-foreground">Loading settings...</div>
        </div>
      </div>
    )
  }

  return (
    <section aria-labelledby="settings-title" className="admin-section">
      <header className="admin-page-header">
        <h1 id="settings-title" className="admin-page-title">
          Admin Settings
        </h1>
        <p className="admin-page-description">
          Configure platform settings including email, payments, commissions, and withdrawals.
        </p>
      </header>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="inline-flex h-auto p-1 bg-muted/50 rounded-xl flex-wrap gap-1">
          <TabsTrigger value="smtp" className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2">
            <Mail className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">SMTP</span>
          </TabsTrigger>
          <TabsTrigger value="payment" className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2">
            <CreditCard className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Payment Gateway</span>
          </TabsTrigger>
          <TabsTrigger value="commission" className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2">
            <Percent className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Agent Commission</span>
          </TabsTrigger>
          <TabsTrigger value="withdraw" className="rounded-lg data-[state=active]:shadow-md px-4 py-2.5 gap-2">
            <Wallet className="h-4 w-4" aria-hidden="true" />
            <span className="hidden sm:inline">Withdrawals</span>
          </TabsTrigger>
        </TabsList>

        {/* SMTP Settings */}
        <TabsContent value="smtp" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center shadow-lg">
                  <Mail className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>SMTP Configuration</CardTitle>
                  <CardDescription>Configure email delivery settings for notifications and alerts.</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={smtpForm.handleSubmit(onSMTPSubmit)} className="space-y-6">
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="smtp-host">SMTP Host</Label>
                    <Input
                      id="smtp-host"
                      placeholder="smtp.gmail.com"
                      {...smtpForm.register("host")}
                      className="rounded-xl"
                    />
                    {smtpForm.formState.errors.host && (
                      <p className="text-sm text-destructive">{smtpForm.formState.errors.host.message}</p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="smtp-port">Port</Label>
                    <Input
                      id="smtp-port"
                      type="number"
                      placeholder="587"
                      {...smtpForm.register("port")}
                      className="rounded-xl"
                    />
                    {smtpForm.formState.errors.port && (
                      <p className="text-sm text-destructive">{smtpForm.formState.errors.port.message}</p>
                    )}
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="smtp-username">Username</Label>
                    <Input
                      id="smtp-username"
                      placeholder="your@email.com"
                      {...smtpForm.register("username")}
                      className="rounded-xl"
                    />
                    {smtpForm.formState.errors.username && (
                      <p className="text-sm text-destructive">{smtpForm.formState.errors.username.message}</p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="smtp-password">Password</Label>
                    <div className="relative">
                      <Input
                        id="smtp-password"
                        type={showSecrets.smtpPassword ? "text" : "password"}
                        placeholder="••••••••"
                        {...smtpForm.register("password")}
                        className="rounded-xl pr-10"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => toggleSecret("smtpPassword")}
                        aria-label={showSecrets.smtpPassword ? "Hide password" : "Show password"}
                      >
                        {showSecrets.smtpPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                    {smtpForm.formState.errors.password && (
                      <p className="text-sm text-destructive">{smtpForm.formState.errors.password.message}</p>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="smtp-encryption">Encryption</Label>
                  <Select
                    value={smtpForm.watch("encryption")}
                    onValueChange={(v) => smtpForm.setValue("encryption", v as "none" | "ssl" | "tls")}
                  >
                    <SelectTrigger id="smtp-encryption" className="rounded-xl">
                      <SelectValue placeholder="Select encryption" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">None</SelectItem>
                      <SelectItem value="ssl">SSL</SelectItem>
                      <SelectItem value="tls">TLS</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="smtp-from-email">From Email</Label>
                    <Input
                      id="smtp-from-email"
                      type="email"
                      placeholder="noreply@teertham.com"
                      {...smtpForm.register("fromEmail")}
                      className="rounded-xl"
                    />
                    {smtpForm.formState.errors.fromEmail && (
                      <p className="text-sm text-destructive">{smtpForm.formState.errors.fromEmail.message}</p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="smtp-from-name">From Name</Label>
                    <Input
                      id="smtp-from-name"
                      placeholder="Teertham"
                      {...smtpForm.register("fromName")}
                      className="rounded-xl"
                    />
                    {smtpForm.formState.errors.fromName && (
                      <p className="text-sm text-destructive">{smtpForm.formState.errors.fromName.message}</p>
                    )}
                  </div>
                </div>

                <div className="flex items-center gap-3 pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={smtpForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Save SMTP Settings
                  </Button>
                  <Button type="button" variant="outline" className="rounded-xl bg-transparent">
                    <Send className="h-4 w-4 mr-2" aria-hidden="true" />
                    Send Test Email
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Payment Gateway Settings */}
        <TabsContent value="payment" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 flex items-center justify-center shadow-lg">
                  <CreditCard className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Cashfree Payment Gateway</CardTitle>
                  <CardDescription>Configure Cashfree API credentials for payment processing.</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={cashfreeForm.handleSubmit(onCashfreeSubmit)} className="space-y-6">
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="cf-app-id">App ID</Label>
                    <Input
                      id="cf-app-id"
                      placeholder="Enter Cashfree App ID"
                      {...cashfreeForm.register("appId")}
                      className="rounded-xl"
                    />
                    {cashfreeForm.formState.errors.appId && (
                      <p className="text-sm text-destructive">{cashfreeForm.formState.errors.appId.message}</p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="cf-secret">Secret Key</Label>
                    <div className="relative">
                      <Input
                        id="cf-secret"
                        type={showSecrets.cfSecret ? "text" : "password"}
                        placeholder="••••••••••••••••"
                        {...cashfreeForm.register("secretKey")}
                        className="rounded-xl pr-10"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => toggleSecret("cfSecret")}
                        aria-label={showSecrets.cfSecret ? "Hide secret" : "Show secret"}
                      >
                        {showSecrets.cfSecret ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                    {cashfreeForm.formState.errors.secretKey && (
                      <p className="text-sm text-destructive">{cashfreeForm.formState.errors.secretKey.message}</p>
                    )}
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="cf-env">Environment</Label>
                    <Select
                      value={cashfreeForm.watch("environment")}
                      onValueChange={(v) => cashfreeForm.setValue("environment", v as "sandbox" | "production")}
                    >
                      <SelectTrigger id="cf-env" className="rounded-xl">
                        <SelectValue placeholder="Select environment" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="sandbox">
                          <div className="flex items-center gap-2">
                            <AlertCircle className="h-4 w-4 text-amber-500" />
                            Sandbox (Testing)
                          </div>
                        </SelectItem>
                        <SelectItem value="production">
                          <div className="flex items-center gap-2">
                            <CheckCircle2 className="h-4 w-4 text-emerald-500" />
                            Production (Live)
                          </div>
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="cf-webhook">Webhook Secret (Optional)</Label>
                    <Input
                      id="cf-webhook"
                      placeholder="Enter webhook secret"
                      {...cashfreeForm.register("webhookSecret")}
                      className="rounded-xl"
                    />
                  </div>
                </div>

                <div className="flex items-center gap-3 pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={cashfreeForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Save Payment Settings
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Agent Commission Settings */}
        <TabsContent value="commission" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-500 flex items-center justify-center shadow-lg">
                  <Percent className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Agent Commission Settings</CardTitle>
                  <CardDescription>Configure commission rates and payout schedules for agents.</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={commissionForm.handleSubmit(onCommissionSubmit)} className="space-y-6">
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="commission-rate">Default Commission Rate (%)</Label>
                    <Input
                      id="commission-rate"
                      type="number"
                      min="0"
                      max="100"
                      step="0.1"
                      {...commissionForm.register("defaultCommissionRate")}
                      className="rounded-xl"
                    />
                    {commissionForm.formState.errors.defaultCommissionRate && (
                      <p className="text-sm text-destructive">
                        {commissionForm.formState.errors.defaultCommissionRate.message}
                      </p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="min-booking">Minimum Booking Value (₹)</Label>
                    <Input
                      id="min-booking"
                      type="number"
                      min="0"
                      {...commissionForm.register("minimumBookingValue")}
                      className="rounded-xl"
                    />
                    {commissionForm.formState.errors.minimumBookingValue && (
                      <p className="text-sm text-destructive">
                        {commissionForm.formState.errors.minimumBookingValue.message}
                      </p>
                    )}
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="payout-schedule">Payout Schedule</Label>
                    <Select
                      value={commissionForm.watch("payoutSchedule")}
                      onValueChange={(v) =>
                        commissionForm.setValue("payoutSchedule", v as "weekly" | "biweekly" | "monthly")
                      }
                    >
                      <SelectTrigger id="payout-schedule" className="rounded-xl">
                        <SelectValue placeholder="Select schedule" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="weekly">Weekly</SelectItem>
                        <SelectItem value="biweekly">Bi-Weekly</SelectItem>
                        <SelectItem value="monthly">Monthly</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="min-payout">Minimum Payout (₹)</Label>
                    <Input
                      id="min-payout"
                      type="number"
                      min="0"
                      {...commissionForm.register("minimumPayout")}
                      className="rounded-xl"
                    />
                    {commissionForm.formState.errors.minimumPayout && (
                      <p className="text-sm text-destructive">
                        {commissionForm.formState.errors.minimumPayout.message}
                      </p>
                    )}
                  </div>
                </div>

                <div className="flex items-center gap-3 pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={commissionForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Save Commission Settings
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Withdraw Settings */}
        <TabsContent value="withdraw" className="space-y-6">
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-amber-500 to-orange-500 flex items-center justify-center shadow-lg">
                  <Wallet className="h-5 w-5 text-white" aria-hidden="true" />
                </div>
                <div>
                  <CardTitle>Withdrawal Settings</CardTitle>
                  <CardDescription>Configure withdrawal limits and available methods.</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={withdrawForm.handleSubmit(onWithdrawSubmit)} className="space-y-6">
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="min-withdraw">Minimum Withdrawal (₹)</Label>
                    <Input
                      id="min-withdraw"
                      type="number"
                      min="0"
                      {...withdrawForm.register("minimumWithdrawal")}
                      className="rounded-xl"
                    />
                    {withdrawForm.formState.errors.minimumWithdrawal && (
                      <p className="text-sm text-destructive">
                        {withdrawForm.formState.errors.minimumWithdrawal.message}
                      </p>
                    )}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="max-withdraw">Maximum Withdrawal (₹)</Label>
                    <Input
                      id="max-withdraw"
                      type="number"
                      min="0"
                      {...withdrawForm.register("maximumWithdrawal")}
                      className="rounded-xl"
                    />
                    {withdrawForm.formState.errors.maximumWithdrawal && (
                      <p className="text-sm text-destructive">
                        {withdrawForm.formState.errors.maximumWithdrawal.message}
                      </p>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="processing-time">Processing Time (Days)</Label>
                  <Input
                    id="processing-time"
                    type="number"
                    min="1"
                    max="30"
                    {...withdrawForm.register("processingTime")}
                    className="rounded-xl"
                  />
                  {withdrawForm.formState.errors.processingTime && (
                    <p className="text-sm text-destructive">{withdrawForm.formState.errors.processingTime.message}</p>
                  )}
                </div>

                <div className="flex items-center gap-3 pt-4">
                  <Button
                    type="submit"
                    className="rounded-xl shadow-lg shadow-primary/25"
                    disabled={withdrawForm.formState.isSubmitting}
                  >
                    <Save className="h-4 w-4 mr-2" aria-hidden="true" />
                    Save Withdrawal Settings
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>

          {/* Withdraw Methods */}
          <Card className="admin-card rounded-xl border-0">
            <CardHeader>
              <CardTitle>Withdrawal Methods</CardTitle>
              <CardDescription>Enable or disable withdrawal methods for agents.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {settings.withdrawMethods.map((method) => (
                <div
                  key={method.id}
                  className="flex items-center justify-between p-4 rounded-xl bg-muted/50 border border-border/50"
                >
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <p className="font-medium">{method.name}</p>
                      <Badge variant={method.isActive ? "default" : "secondary"} className="rounded-lg text-xs">
                        {method.isActive ? "Active" : "Disabled"}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">{method.description}</p>
                  </div>
                  <Switch
                    checked={method.isActive}
                    onCheckedChange={() => toggleWithdrawMethod(method)}
                    aria-label={`Toggle ${method.name}`}
                  />
                </div>
              ))}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </section>
  )
}
