"use client"

import { useState, useEffect } from "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 { Separator } from "@/components/ui/separator"
import { settingsApi, credentialsApi, ConfiguredService, storageApi } from "@/lib/api"
import { toast } from "sonner"
import { Loader2, Check, Key } from "lucide-react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"

interface ThemeConfig {
    logoUrl: string
    primaryColor: string
    companyName: string
}

const DEFAULT_THEME: ThemeConfig = {
    logoUrl: "/logo.png",
    primaryColor: "#000000",
    companyName: "GoHorseJobs"
}

export default function SettingsPage() {
    const [config, setConfig] = useState<ThemeConfig>(DEFAULT_THEME)
    const [loading, setLoading] = useState(true)
    const [saving, setSaving] = useState(false)

    // Credentials State
    const [credentials, setCredentials] = useState<ConfiguredService[]>([])
    const [loadingCredentials, setLoadingCredentials] = useState(false)
    const [selectedService, setSelectedService] = useState<string | null>(null)
    const [credentialPayload, setCredentialPayload] = useState<any>({})
    const [isDialogOpen, setIsDialogOpen] = useState(false)
    const [testingConnection, setTestingConnection] = useState(false)

    const handleTestStorageConnection = async () => {
        setTestingConnection(true)
        try {
            const res = await storageApi.testConnection()
            toast.success(res.message || "Connection successful")
        } catch (error: any) {
            console.error("Storage connection test failed", error)
            toast.error(error.message || "Connection failed")
        } finally {
            setTestingConnection(false)
        }
    }

    const fetchSettings = async () => {
        try {
            const data = await settingsApi.get("theme")
            if (data && Object.keys(data).length > 0) {
                setConfig({ ...DEFAULT_THEME, ...data })
            }
        } catch (error) {
            console.error("Failed to fetch theme settings", error)
        }
    }

    const fetchCredentials = async () => {
        setLoadingCredentials(true)
        try {
            const res = await credentialsApi.list()
            // Ensure we handle the response correctly (api.ts wraps it in { services: ... })
            if (res && res.services) {
                setCredentials(res.services)
            }
        } catch (error) {
            console.error("Failed to fetch credentials", error)
            toast.error("Failed to load credentials status")
        } finally {
            setLoadingCredentials(false)
        }
    }

    useEffect(() => {
        Promise.all([fetchSettings(), fetchCredentials()]).finally(() => setLoading(false))
    }, [])

    const handleSaveTheme = async () => {
        setSaving(true)
        try {
            await settingsApi.save("theme", config)
            toast.success("Theme settings saved")
            window.location.reload()
        } catch (error) {
            console.error("Failed to save settings", error)
            toast.error("Failed to save settings")
        } finally {
            setSaving(false)
        }
    }



    if (loading) {
        return <div className="flex justify-center p-8"><Loader2 className="animate-spin" /></div>
    }

    // Predefined schemas for known services (Copied from CredentialsPage)
    const schemas: Record<string, { label: string, fields: { key: string, label: string, type?: string }[] }> = {
        stripe: {
            label: "Stripe",
            fields: [
                { key: "secretKey", label: "Secret Key (sk_...)", type: "password" },
                { key: "webhookSecret", label: "Webhook Secret (whsec_...)", type: "password" },
                { key: "publishableKey", label: "Publishable Key (pk_...)", type: "text" },
            ]
        },
        payment_gateway: {
            label: "Gateway de Pagamento (Fictício)",
            fields: [
                { key: "merchantId", label: "Merchant ID", type: "text" },
                { key: "apiKey", label: "API Key", type: "password" },
                { key: "endpoint", label: "Endpoint URL", type: "text" },
                { key: "webhookSecret", label: "Webhook Secret", type: "password" },
            ]
        },
        storage: {
            label: "AWS S3 / Compatible",
            fields: [
                { key: "endpoint", label: "Endpoint URL", type: "text" },
                { key: "region", label: "Region", type: "text" },
                { key: "bucket", label: "Bucket Name", type: "text" },
                { key: "accessKey", label: "Access Key ID", type: "text" },
                { key: "secretKey", label: "Secret Access Key", type: "password" },
            ]
        },
        cpanel: {
            label: "cPanel Integration",
            fields: [
                { key: "host", label: "cPanel URL (https://domain:2083)", type: "text" },
                { key: "username", label: "Username", type: "text" },
                { key: "apiToken", label: "API Token", type: "password" },
            ]
        },
        lavinmq: {
            label: "LavinMQ (AMQP)",
            fields: [
                { key: "amqpUrl", label: "AMQP URL", type: "password" },
            ]
        },
        cloudflare_config: {
            label: "Cloudflare",
            fields: [
                { key: "apiToken", label: "API Token", type: "password" },
                { key: "zoneId", label: "Zone ID", type: "text" },
            ]
        },
        smtp: {
            label: "SMTP Email",
            fields: [
                { key: "host", label: "Host", type: "text" },
                { key: "port", label: "Port", type: "number" },
                { key: "username", label: "Username", type: "text" },
                { key: "password", label: "Password", type: "password" },
                { key: "from_email", label: "From Email", type: "email" },
                { key: "from_name", label: "From Name", type: "text" },
                { key: "secure", label: "Use TLS", type: "checkbox" }
            ]
        },
        appwrite: {
            label: "Appwrite",
            fields: [
                { key: "endpoint", label: "Endpoint", type: "text" },
                { key: "projectId", label: "Project ID", type: "text" },
                { key: "apiKey", label: "API Key", type: "password" },
            ]
        },
        firebase: {
            label: "Firebase (JSON)",
            fields: [
                { key: "serviceAccountJson", label: "Service Account JSON Content", type: "textarea" }
            ]
        }
    }

    const configuredMap = new Map(credentials.map((svc) => [svc.service_name, svc]))
    const servicesToRender: ConfiguredService[] = Array.from(
        new Set([...Object.keys(schemas), ...credentials.map((svc) => svc.service_name)])
    ).map((serviceName) => configuredMap.get(serviceName) || {
        service_name: serviceName,
        updated_at: "",
        updated_by: "",
        is_configured: false,
    })

    const handleOpenCredentialDialog = (serviceName: string) => {
        setSelectedService(serviceName)
        setCredentialPayload({})
        setIsDialogOpen(true)
    }

    const handleSaveCredential = async () => {
        if (!selectedService) return

        setSaving(true)
        try {
            await credentialsApi.save(selectedService, credentialPayload)
            toast.success(`Credentials for ${schemas[selectedService]?.label || selectedService} saved`)
            setIsDialogOpen(false)
            fetchCredentials()
        } catch (error) {
            console.error("Failed to save credential", error)
            toast.error("Failed to save credential")
        } finally {
            setSaving(false)
        }
    }

    // ... existing imports ...
    // Note: State definition needs update to object payload
    // const [credentialPayload, setCredentialPayload] = useState<any>({})

    const isSelectedConfigured = selectedService ? configuredMap.has(selectedService) : false

    return (
        <div className="space-y-6">
            {/* Header ... */}
            <div>
                <h1 className="text-3xl font-bold tracking-tight">System Settings</h1>
                <p className="text-muted-foreground">Manage application appearance and integrations.</p>
            </div>
            <Separator />

            <Tabs defaultValue="integrations" className="space-y-4"> {/* Default to integrations for visibility */}
                <TabsList>
                    <TabsTrigger value="theme">Branding & Theme</TabsTrigger>
                    <TabsTrigger value="integrations">Integrations & Credentials</TabsTrigger>
                </TabsList>

                {/* Theme Tab Content (unchanged) */}
                <TabsContent value="theme" className="space-y-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>Branding & Theme</CardTitle>
                            <CardDescription>Customize the look and feel of your dashboard.</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="grid gap-2">
                                <Label htmlFor="companyName">Company Name</Label>
                                <Input
                                    id="companyName"
                                    value={config.companyName}
                                    onChange={(e) => setConfig({ ...config, companyName: e.target.value })}
                                />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="logoUrl">Logo URL</Label>
                                <div className="flex gap-4 items-center">
                                    <Input
                                        id="logoUrl"
                                        value={config.logoUrl}
                                        onChange={(e) => setConfig({ ...config, logoUrl: e.target.value })}
                                    />
                                    {config.logoUrl && (
                                        <div className="h-10 w-10 border rounded bg-muted flex items-center justify-center overflow-hidden">
                                            <img src={config.logoUrl} alt="Preview" className="max-h-full max-w-full" onError={(e) => e.currentTarget.style.display = 'none'} />
                                        </div>
                                    )}
                                </div>
                                <p className="text-xs text-muted-foreground">Enter a public URL for your logo.</p>
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="primaryColor">Primary Color</Label>
                                <div className="flex gap-4 items-center">
                                    <Input
                                        id="primaryColor"
                                        type="color"
                                        className="w-20 h-10 p-1 cursor-pointer"
                                        value={config.primaryColor}
                                        onChange={(e) => setConfig({ ...config, primaryColor: e.target.value })}
                                    />
                                    <div className="flex-1 p-2 rounded text-white text-center text-sm" style={{ backgroundColor: config.primaryColor }}>
                                        Sample Button
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                        <div className="p-6 pt-0 flex justify-end">
                            <Button onClick={handleSaveTheme} disabled={saving}>
                                {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                Save Changes
                            </Button>
                        </div>
                    </Card>
                </TabsContent>

                <TabsContent value="integrations" className="space-y-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>External Services</CardTitle>
                            <CardDescription>Manage credentials for third-party integrations securely. Keys are encrypted and locked after saving.</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                                {servicesToRender.map((svc) => (
                                    <div key={svc.service_name} className="flex flex-col justify-between border rounded-lg p-4 hover:bg-muted/50 transition-colors">
                                        <div className="space-y-2 mb-4">
                                            <div className="flex items-center justify-between">
                                                <p className="font-semibold capitalize">{schemas[svc.service_name]?.label || svc.service_name}</p>
                                                {svc.is_configured ? (
                                                    <Badge variant="default" className="bg-green-600/20 text-green-700 hover:bg-green-600/30">
                                                        <Check className="w-3 h-3 mr-1" /> Active
                                                    </Badge>
                                                ) : (
                                                    <Badge variant="outline">Pending</Badge>
                                                )}
                                            </div>
                                            <p className="text-xs text-muted-foreground">
                                                {svc.is_configured
                                                    ? `Updated ${new Date(svc.updated_at).toLocaleDateString()}`
                                                    : 'Not configured'}
                                            </p>
                                        </div>
                                        <div className="flex items-center gap-2 mt-auto">
                                            {svc.service_name === 'storage' && svc.is_configured && (
                                                <Button variant="secondary" size="sm" className="w-full mb-2" onClick={handleTestStorageConnection} disabled={testingConnection}>
                                                    {testingConnection ? <Loader2 className="w-3 h-3 animate-spin mr-1" /> : "Test Connection"}
                                                </Button>
                                            )}
                                            <div className="flex w-full gap-2">
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    className="w-full"
                                                    onClick={() => handleOpenCredentialDialog(svc.service_name)}
                                                    disabled={svc.is_configured}
                                                >
                                                    <Key className="w-3 h-3 mr-2" />
                                                    {svc.is_configured ? "Configured" : "Setup"}
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>

            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Configure {selectedService && (schemas[selectedService]?.label || selectedService)}</DialogTitle>
                        <DialogDescription>
                            Enter credentials. Keys are encrypted before storage, hidden after saving, and cannot be edited later.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">
                        {selectedService && schemas[selectedService]?.fields.map((field) => (
                            <div key={field.key} className="space-y-2">
                                <Label htmlFor={field.key}>{field.label}</Label>
                                {field.type === 'textarea' ? (
                                    <Textarea
                                        id={field.key}
                                        className="font-mono text-xs min-h-[80px]"
                                        value={(credentialPayload as any)[field.key] || ""}
                                        onChange={(e) => setCredentialPayload({ ...credentialPayload, [field.key]: e.target.value })}
                                        placeholder={isSelectedConfigured ? "Stored securely" : `Enter ${field.label}`}
                                    />
                                ) : (
                                    <Input
                                        id={field.key}
                                        type={field.type === 'checkbox' ? 'checkbox' : field.type}
                                        // TODO: Checkbox handling if needed
                                        value={(credentialPayload as any)[field.key] || ""}
                                        onChange={(e) => setCredentialPayload({ ...credentialPayload, [field.key]: e.target.value })}
                                        placeholder={isSelectedConfigured ? "Stored securely" : `Enter ${field.label}`}
                                    />
                                )}
                            </div>
                        ))}
                        {/* Fallback for unknown services if any */}
                        {selectedService && !schemas[selectedService] && (
                            <div className="p-4 text-sm text-yellow-600 bg-yellow-50 rounded">
                                Usage schema not defined for this service.
                            </div>
                        )}
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                        <Button onClick={handleSaveCredential} disabled={saving}>
                            {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Save Credentials
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
