'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/store/store';
import { fetchBrandConfig, updateBrandConfig } from '@/store/slices/adminSlice';
import Link from 'next/link';
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 { Separator } from '@/components/ui/separator';
import { ArrowLeft, Plus, Trash2, Upload } from 'lucide-react';
import { toast } from 'sonner';

export default function BrandConfigPage() {
  const params = useParams();
  const clientId = params.id as string;
  const dispatch = useDispatch<AppDispatch>();
  const { brandConfig } = useSelector((state: RootState) => state.admin);

  const [primaryColors, setPrimaryColors] = useState<string[]>([]);
  const [secondaryColors, setSecondaryColors] = useState<string[]>([]);
  const [fonts, setFonts] = useState({ heading: '', body: '', accent: '' });
  const [voiceRules, setVoiceRules] = useState('');
  const [voiceExamples, setVoiceExamples] = useState<Array<{ good: string; bad: string }>>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      await dispatch(fetchBrandConfig(clientId));
      setLoading(false);
    };
    load();
  }, [dispatch, clientId]);

  useEffect(() => {
    if (brandConfig) {
      setPrimaryColors(brandConfig.primary_colors || []);
      setSecondaryColors(brandConfig.secondary_colors || []);
      setFonts(brandConfig.fonts as any || { heading: '', body: '', accent: '' });
      setVoiceRules(brandConfig.voice_rules || '');
      setVoiceExamples(brandConfig.voice_examples || []);
    }
  }, [brandConfig]);

  const handleSave = async () => {
    setSaving(true);
    try {
      await dispatch(
        updateBrandConfig({
          clientId,
          data: {
            primary_colors: primaryColors,
            secondary_colors: secondaryColors,
            fonts,
            voice_rules: voiceRules,
            voice_examples: voiceExamples,
          },
        })
      ).unwrap();
      toast.success('Brand config saved');
    } catch {
      toast.error('Failed to save brand config');
    } finally {
      setSaving(false);
    }
  };

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const res = await fetch(`/api/v1/admin/clients/${clientId}/brand/logo`, {
        method: 'POST',
        body: formData,
      });
      if (res.ok) {
        toast.success('Logo uploaded');
        dispatch(fetchBrandConfig(clientId));
      } else {
        toast.error('Failed to upload logo');
      }
    } catch {
      toast.error('Upload error');
    }
  };

  const handleDeleteLogo = async (index: number) => {
    try {
      const res = await fetch(`/api/v1/admin/clients/${clientId}/brand/logo/${index}`, {
        method: 'DELETE',
      });
      if (res.ok) {
        toast.success('Logo removed');
        dispatch(fetchBrandConfig(clientId));
      }
    } catch {
      toast.error('Failed to remove logo');
    }
  };

  const handleGuidelineUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const res = await fetch(`/api/v1/admin/clients/${clientId}/brand/guideline`, {
        method: 'POST',
        body: formData,
      });
      if (res.ok) {
        toast.success('Guideline uploaded');
        dispatch(fetchBrandConfig(clientId));
      } else {
        toast.error('Failed to upload guideline');
      }
    } catch {
      toast.error('Upload error');
    }
  };

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="h-8 w-64 bg-gray-200 rounded animate-pulse" />
        <div className="h-96 bg-gray-200 rounded animate-pulse" />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-3xl">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href={`/admin/clients/${clientId}`}>
            <Button variant="ghost" size="sm">
              <ArrowLeft className="w-4 h-4 mr-1" />Back
            </Button>
          </Link>
          <h1 className="text-2xl font-semibold">Brand Configuration</h1>
        </div>
        <Button onClick={handleSave} disabled={saving}>
          {saving ? 'Saving...' : 'Save Changes'}
        </Button>
      </div>

      {/* Colors */}
      <div className="bg-white rounded-lg border p-6 space-y-4">
        <h2 className="text-lg font-medium">Colors</h2>

        <div className="space-y-2">
          <Label>Primary Colors</Label>
          <div className="flex flex-wrap gap-2">
            {primaryColors.map((color, i) => (
              <div key={i} className="flex items-center gap-1">
                <input
                  type="color"
                  value={color}
                  onChange={(e) => {
                    const updated = [...primaryColors];
                    updated[i] = e.target.value;
                    setPrimaryColors(updated);
                  }}
                  className="w-10 h-10 rounded cursor-pointer border"
                />
                <button
                  onClick={() => setPrimaryColors(primaryColors.filter((_, idx) => idx !== i))}
                  className="text-gray-400 hover:text-red-500"
                >
                  <Trash2 className="w-3 h-3" />
                </button>
              </div>
            ))}
            <button
              onClick={() => setPrimaryColors([...primaryColors, '#5146E5'])}
              className="w-10 h-10 border-2 border-dashed border-gray-300 rounded flex items-center justify-center text-gray-400 hover:text-gray-600"
            >
              <Plus className="w-4 h-4" />
            </button>
          </div>
        </div>

        <div className="space-y-2">
          <Label>Secondary Colors</Label>
          <div className="flex flex-wrap gap-2">
            {secondaryColors.map((color, i) => (
              <div key={i} className="flex items-center gap-1">
                <input
                  type="color"
                  value={color}
                  onChange={(e) => {
                    const updated = [...secondaryColors];
                    updated[i] = e.target.value;
                    setSecondaryColors(updated);
                  }}
                  className="w-10 h-10 rounded cursor-pointer border"
                />
                <button
                  onClick={() => setSecondaryColors(secondaryColors.filter((_, idx) => idx !== i))}
                  className="text-gray-400 hover:text-red-500"
                >
                  <Trash2 className="w-3 h-3" />
                </button>
              </div>
            ))}
            <button
              onClick={() => setSecondaryColors([...secondaryColors, '#E9E8F8'])}
              className="w-10 h-10 border-2 border-dashed border-gray-300 rounded flex items-center justify-center text-gray-400 hover:text-gray-600"
            >
              <Plus className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      <Separator />

      {/* Fonts */}
      <div className="bg-white rounded-lg border p-6 space-y-4">
        <h2 className="text-lg font-medium">Fonts</h2>
        <div className="grid grid-cols-3 gap-4">
          <div className="space-y-1">
            <Label htmlFor="font-heading">Heading Font</Label>
            <Input
              id="font-heading"
              value={fonts.heading}
              onChange={(e) => setFonts({ ...fonts, heading: e.target.value })}
              placeholder="e.g. Inter"
            />
          </div>
          <div className="space-y-1">
            <Label htmlFor="font-body">Body Font</Label>
            <Input
              id="font-body"
              value={fonts.body}
              onChange={(e) => setFonts({ ...fonts, body: e.target.value })}
              placeholder="e.g. Roboto"
            />
          </div>
          <div className="space-y-1">
            <Label htmlFor="font-accent">Accent Font</Label>
            <Input
              id="font-accent"
              value={fonts.accent}
              onChange={(e) => setFonts({ ...fonts, accent: e.target.value })}
              placeholder="e.g. Instrument Sans"
            />
          </div>
        </div>
      </div>

      <Separator />

      {/* Logos */}
      <div className="bg-white rounded-lg border p-6 space-y-4">
        <h2 className="text-lg font-medium">Logos</h2>
        <div className="flex flex-wrap gap-4">
          {brandConfig?.logo_paths?.map((path, i) => (
            <div key={i} className="relative group">
              <div className="w-24 h-24 bg-gray-100 rounded border flex items-center justify-center overflow-hidden">
                <span className="text-xs text-gray-500 text-center px-1 break-all">
                  {path.split('/').pop()}
                </span>
              </div>
              <button
                onClick={() => handleDeleteLogo(i)}
                className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <Trash2 className="w-3 h-3" />
              </button>
            </div>
          ))}
          <label className="w-24 h-24 border-2 border-dashed border-gray-300 rounded flex flex-col items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer">
            <Upload className="w-5 h-5 mb-1" />
            <span className="text-xs">Upload</span>
            <input type="file" accept="image/*" onChange={handleLogoUpload} className="hidden" />
          </label>
        </div>
      </div>

      <Separator />

      {/* Voice Rules */}
      <div className="bg-white rounded-lg border p-6 space-y-4">
        <h2 className="text-lg font-medium">Brand Voice</h2>
        <div className="space-y-2">
          <Label htmlFor="voice-rules">Voice Rules</Label>
          <Textarea
            id="voice-rules"
            value={voiceRules}
            onChange={(e) => setVoiceRules(e.target.value)}
            placeholder="Describe the brand's tone of voice, writing style, key phrases to use or avoid..."
            rows={4}
          />
        </div>

        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <Label>Voice Examples (Good / Bad)</Label>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setVoiceExamples([...voiceExamples, { good: '', bad: '' }])}
            >
              <Plus className="w-3 h-3 mr-1" />Add Example
            </Button>
          </div>
          {voiceExamples.map((ex, i) => (
            <div key={i} className="flex gap-2 items-start">
              <div className="flex-1 space-y-1">
                <Input
                  value={ex.good}
                  onChange={(e) => {
                    const updated = [...voiceExamples];
                    updated[i] = { ...updated[i], good: e.target.value };
                    setVoiceExamples(updated);
                  }}
                  placeholder="Good example"
                  className="border-green-200 focus:ring-green-500"
                />
              </div>
              <div className="flex-1 space-y-1">
                <Input
                  value={ex.bad}
                  onChange={(e) => {
                    const updated = [...voiceExamples];
                    updated[i] = { ...updated[i], bad: e.target.value };
                    setVoiceExamples(updated);
                  }}
                  placeholder="Bad example"
                  className="border-red-200 focus:ring-red-500"
                />
              </div>
              <button
                onClick={() => setVoiceExamples(voiceExamples.filter((_, idx) => idx !== i))}
                className="mt-2 text-gray-400 hover:text-red-500"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          ))}
        </div>
      </div>

      <Separator />

      {/* Brand Guideline */}
      <div className="bg-white rounded-lg border p-6 space-y-4">
        <h2 className="text-lg font-medium">Brand Guideline Document</h2>
        {brandConfig?.guideline_doc_path ? (
          <p className="text-sm text-gray-600">
            Current: <span className="font-mono">{brandConfig.guideline_doc_path.split('/').pop()}</span>
          </p>
        ) : (
          <p className="text-sm text-gray-500">No guideline uploaded yet.</p>
        )}
        <label className="inline-flex items-center gap-2 px-4 py-2 border rounded-lg cursor-pointer hover:bg-gray-50 text-sm">
          <Upload className="w-4 h-4" />
          Upload Guideline (PDF/DOCX)
          <input type="file" accept=".pdf,.docx" onChange={handleGuidelineUpload} className="hidden" />
        </label>
      </div>
    </div>
  );
}
