'use client';

import React, { useState } from 'react';
import { Settings, Save, ShieldAlert, Sliders, RefreshCw, Layers, Database, FileText, Upload, Eye } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useSettings, useUploadAgreementPdf, useUpsertSetting } from '@/services/settings/queries';
import toast from 'react-hot-toast';
import { getAssetUrl } from '@/lib/getAssetUrl';

type SettingsGroup = 'general' | 'auth' | 'notifications' | 'lms' | 'agreements';

export default function SettingsManagementPage() {
  const [activeGroup, setActiveGroup] = useState<SettingsGroup>('general');
  const { data: settings = [], isLoading, isError, refetch } = useSettings(activeGroup);
  const upsertMutation = useUpsertSetting();
  const uploadPdfMutation = useUploadAgreementPdf();

  const [editCache, setEditCache] = useState<Record<string, string>>({});

  const handleValueChange = (key: string, value: string) => {
    setEditCache((prev) => ({ ...prev, [key]: value }));
  };

  const handleFileUpload = (key: string, event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (file.type !== 'application/pdf') {
        toast.error('Please upload a valid PDF file.');
        return;
      }
      uploadPdfMutation.mutate({ key, file });
    }
  };

  const commitSettingUpdate = async (key: string, currentGroup: string) => {
    const rawValue = editCache[key];
    if (rawValue === undefined) return;

    let parsedValue: any = rawValue;
    try {
      if ((rawValue.startsWith('{') && rawValue.endsWith('}')) || 
          (rawValue.startsWith('[') && rawValue.endsWith(']'))) {
        parsedValue = JSON.parse(rawValue);
      }
    } catch (e) {
      // Keep as string on parse failure
    }

    upsertMutation.mutate({
      key,
      data: {
        value: parsedValue,
        group: currentGroup,
      },
    });
  };

  console.log('Current Settings State:', settings);

  if (isLoading) {
    return (
      <div className="p-8 space-y-4 max-w-7xl mx-auto animate-pulse">
        <div className="h-10 bg-muted/40 rounded-lg w-1/4 mb-6" />
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          <div className="space-y-2 col-span-1">
            {[...Array(5)].map((_, i) => <div key={i} className="h-9 bg-muted/40 rounded-lg" />)}
          </div>
          <div className="col-span-3 space-y-4">
            {[...Array(3)].map((_, i) => <div key={i} className="h-32 bg-muted/40 rounded-xl border border-border/20" />)}
          </div>
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="p-8 text-center text-sm text-destructive border border-dashed border-destructive/20 rounded-xl bg-destructive/5 max-w-7xl mx-auto">
        Fatal Topology Link Breakdown: Unable to download system environment variables from remote cluster storage blocks.
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-7xl mx-auto animate-in fade-in duration-300 select-none">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-border/10 pb-5">
        <div className="flex flex-col gap-0.5">
          <h1 className="text-md font-bold tracking-tight text-foreground uppercase flex items-center gap-2">
            <Settings className="h-4 w-4 text-primary animate-spin-slow" /> SYSTEM VARIABLES ENGINE
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/80">Configure application-wide parameters, business logic thresholds, and operational flags.</p>
        </div>
        <div>
          <Button 
            onClick={() => refetch()} 
            variant="outline"
            className="h-8 rounded-lg px-3 text-xs font-semibold border-border/40 hover:bg-muted text-foreground flex items-center gap-1.5"
          >
            <RefreshCw className="h-3.5 w-3.5" /> Re-sync State Matrices
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 items-start">
        <div className="flex flex-row lg:flex-col overflow-x-auto gap-1 bg-muted/20 border border-border/40 p-1.5 rounded-xl lg:w-full">
          {[
            { id: 'general', label: 'General System', icon: Sliders },
            { id: 'auth', label: 'RBAC & Auth Matrix', icon: ShieldAlert },
            { id: 'notifications', label: 'Broadcast Filters', icon: Layers },
            { id: 'lms', label: 'LMS Engine Parameters', icon: Database },
            { id: 'agreements', label: 'Agreements & Compliance', icon: FileText },
          ].map((tab) => {
            const Icon = tab.icon;
            const isSelected = activeGroup === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => { setActiveGroup(tab.id as SettingsGroup); setEditCache({}); }}
                className={`flex items-center gap-2.5 px-3 py-2 text-xs font-semibold rounded-lg whitespace-nowrap transition-all duration-150 ${
                  isSelected 
                    ? 'bg-primary text-primary-foreground shadow-sm' 
                    : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                }`}
              >
                <Icon className={`h-3.5 w-3.5 ${isSelected ? 'text-primary-foreground' : 'text-primary'}`} />
                <span>{tab.label}</span>
              </button>
            );
          })}
        </div>

        <div className="lg:col-span-3 space-y-4">
          {settings.length === 0 ? (
            <div className="p-12 text-center text-xs text-muted-foreground/60 border border-dashed border-border/40 bg-card/20 rounded-xl">
              No parameter configurations mapped to this cluster group node structure.
            </div>
          ) : (
            settings.map((setting) => {
              const displayString = editCache[setting.key] ?? (
                typeof setting.value === 'object' 
                  ? JSON.stringify(setting.value, null, 2) 
                  : String(setting.value)
              );
              const isDirty = editCache[setting.key] !== undefined;
              const isAgreementGroup = activeGroup === 'agreements';

              return (
                <Card key={setting.key} className="shadow-sm rounded-xl border border-border/40 bg-card/40 hover:border-border transition-colors">
                  <CardHeader className="pb-3 flex flex-row items-start justify-between space-y-0 gap-4">
                    <div className="space-y-1">
                      <CardTitle className="text-xs font-bold font-mono text-primary uppercase tracking-wide">
                        {setting.key.replace(/_/g, ' ')}
                      </CardTitle>
                      <CardDescription className="text-[11px] text-muted-foreground/70">
                        Node Key: <code className="text-foreground bg-muted px-1 py-0.5 rounded text-[10px]">{setting.key}</code>
                      </CardDescription>
                    </div>

                    {!isAgreementGroup && (
                      <Button
                        size="sm"
                        onClick={() => commitSettingUpdate(setting.key, setting.group)}
                        disabled={!isDirty || upsertMutation.isPending}
                        className="h-7 text-[10px] px-2.5 rounded-md font-semibold bg-primary text-primary-foreground shadow-sm transition-transform duration-150 active:scale-95 disabled:opacity-40 flex items-center gap-1"
                      >
                        <Save className="h-3 w-3 stroke-[2.5]" />
                        <span>{upsertMutation.isPending ? 'Syncing...' : 'Commit'}</span>
                      </Button>
                    )}
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {isAgreementGroup ? (
                      <div className="flex flex-col gap-3 p-3 bg-muted/20 border border-border/40 rounded-lg">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <FileText className="h-4 w-4 text-primary" />
                            <span className="text-xs font-semibold">
                              {typeof setting.value === 'object' && (setting.value as any)?.fileName
                                ? (setting.value as any).fileName
                                : 'No PDF Document Uploaded'}
                            </span>
                          </div>
                          {typeof setting.value === 'object' && (setting.value as any)?.fileUrl && (
                            <a
                              href={getAssetUrl((setting.value as any)?.fileUrl)}
                              target="_blank"
                              rel="noreferrer"
                              className="text-[11px] text-primary hover:underline flex items-center gap-1 font-medium"
                            >
                              <Eye className="h-3.5 w-3.5" /> Preview PDF
                            </a>
                          )}
                        </div>

                        <div className="flex items-center gap-2 pt-1">
                          <label className="cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90 px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1.5 transition-all">
                            <Upload className="h-3.5 w-3.5" />
                            <span>{(setting.value as any)?.fileUrl ? 'Replace PDF' : 'Upload PDF'}</span>
                            <input
                              type="file"
                              accept="application/pdf"
                              className="hidden"
                              onChange={(e) => handleFileUpload(setting.key, e)}
                            />
                          </label>
                          {uploadPdfMutation.isPending && (
                            <span className="text-[11px] text-muted-foreground animate-pulse">
                              Uploading document...
                            </span>
                          )}
                        </div>
                      </div>
                    ) : (
                      <div className="flex flex-col gap-1.5">
                        <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/60">Live Value Structure Mapping</label>
                        <textarea
                          rows={typeof setting.value === 'object' ? 5 : 2}
                          value={displayString}
                          onChange={(e) => handleValueChange(setting.key, e.target.value)}
                          className="w-full font-mono text-xs bg-background border border-border/40 rounded-lg p-2.5 text-foreground placeholder:text-muted-foreground/30 focus-visible:outline-none focus-visible:border-primary transition-colors resize-y"
                        />
                      </div>
                    )}

                    {setting.updatedBy && (
                      <div className="text-[9px] text-muted-foreground/40 font-mono text-right">
                        Last Mutation Actor Reference Block ID: {setting.updatedBy}
                      </div>
                    )}
                  </CardContent>
                </Card>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}