import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, RotateCcw, Eye, Pencil } from 'lucide-react';

const STAGE_KEYS = ['First Notice', 'Second Notice', 'Third & Final Notice'];

const DEFAULT_TEMPLATES = {
  'First Notice': `During a recent inspection of the community, we noted that your property is out of compliance with {{associationName}}'s Covenants, Conditions, and Restrictions (CC&Rs). Your property violates the governing documents, including, but not limited to, the referenced section below. This notice is being sent as an initial friendly reminder asking that you correct the situation listed below. Please take the necessary steps to correct the situation by {{dueDate}} to avoid further action.`,
  'Second Notice': `This letter serves as a SECOND NOTICE regarding the violation at your property. A recent inspection has confirmed that the condition previously cited has not been corrected. As a member of the {{associationName}}, you are required to maintain your property in accordance with the community's governing documents. Please rectify this violation by {{dueDate}} to avoid further escalation of this matter.`,
  'Third & Final Notice': `This is a FINAL NOTICE regarding the ongoing violation on your property. Despite previous communications, the violation remains uncorrected. Failure to remedy this situation by {{dueDate}} may result in the imposition of fines, suspension of use rights, or legal action as authorized by the {{associationName}}'s governing documents and Florida Statutes. Please treat this matter with urgency.`,
};

const VARIABLES = [
  { key: 'ownerName', label: 'Owner Name', sample: 'Jane Smith' },
  { key: 'address', label: 'Property Address', sample: '123 Main St' },
  { key: 'associationName', label: 'Association Name', sample: 'Sunset HOA' },
  { key: 'dueDate', label: 'Due Date', sample: 'January 31, 2026' },
];

const fillPreview = (tpl) =>
  VARIABLES.reduce((acc, v) => acc.replaceAll(`{{${v.key}}}`, v.sample), tpl || '');

export default function ViolationTypeDialog({ open, onOpenChange, violationType, associationId, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [activeStage, setActiveStage] = useState('First Notice');
  const [previewMode, setPreviewMode] = useState(false);
  const textareaRefs = useRef({});
  const [formData, setFormData] = useState({
    category: '', article_section: '', citation: '', requested_action: '',
    cure_days: 14, stage_count: 3,
    letter_templates: { 'First Notice': '', 'Second Notice': '', 'Third & Final Notice': '' },
  });

  useEffect(() => {
    if (violationType) {
      const tpl = violationType.letter_templates || {};
      setFormData({
        category: violationType.category || '',
        article_section: violationType.article_section || '',
        citation: violationType.citation || '',
        requested_action: violationType.requested_action || '',
        cure_days: violationType.cure_days ?? 14,
        stage_count: violationType.stage_count ?? 3,
        letter_templates: {
          'First Notice': tpl['First Notice'] || '',
          'Second Notice': tpl['Second Notice'] || '',
          'Third & Final Notice': tpl['Third & Final Notice'] || '',
        },
      });
    } else {
      setFormData({
        category: '', article_section: '', citation: '', requested_action: '',
        cure_days: 14, stage_count: 3,
        letter_templates: { 'First Notice': '', 'Second Notice': '', 'Third & Final Notice': '' },
      });
    }
    setActiveStage('First Notice');
    setPreviewMode(false);
  }, [violationType, open]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!associationId) { toast({ variant: 'destructive', title: 'Error', description: 'No association context found.' }); return; }
    setLoading(true);
    try {
      const payload = {
        association_id: associationId,
        category: formData.category,
        article_section: formData.article_section,
        citation: formData.citation,
        requested_action: formData.requested_action,
        cure_days: Math.max(1, parseInt(formData.cure_days, 10) || 14),
        stage_count: Math.min(3, Math.max(1, parseInt(formData.stage_count, 10) || 3)),
        letter_templates: formData.letter_templates,
      };
      let error;
      if (violationType) {
        ({ error } = await supabase.from('violation_types').update(payload).eq('id', violationType.id));
      } else {
        ({ error } = await supabase.from('violation_types').insert([payload]));
      }
      if (error) throw error;
      toast({ title: 'Success', description: `Violation type ${violationType ? 'updated' : 'created'}.` });
      onSuccess?.();
      onOpenChange(false);
    } catch (err) {
      console.error(err);
      toast({ variant: 'destructive', title: 'Error', description: err?.message || 'Failed to save violation type.' });
    } finally { setLoading(false); }
  };

  const stageCount = Math.min(3, Math.max(1, parseInt(formData.stage_count, 10) || 1));
  const visibleStages = STAGE_KEYS.slice(0, stageCount);

  useEffect(() => {
    if (!visibleStages.includes(activeStage)) setActiveStage(visibleStages[0]);
  }, [stageCount]); // eslint-disable-line

  const setStageTemplate = (stage, value) => {
    setFormData(p => ({ ...p, letter_templates: { ...p.letter_templates, [stage]: value } }));
  };

  const insertVariable = (stage, key) => {
    const ta = textareaRefs.current[stage];
    const token = `{{${key}}}`;
    const current = formData.letter_templates[stage] || '';
    if (!ta) { setStageTemplate(stage, current + token); return; }
    const start = ta.selectionStart ?? current.length;
    const end = ta.selectionEnd ?? current.length;
    const next = current.slice(0, start) + token + current.slice(end);
    setStageTemplate(stage, next);
    requestAnimationFrame(() => {
      ta.focus();
      const pos = start + token.length;
      ta.setSelectionRange(pos, pos);
    });
  };

  const loadDefault = (stage) => setStageTemplate(stage, DEFAULT_TEMPLATES[stage] || '');
  const clearStage = (stage) => setStageTemplate(stage, '');

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[860px] max-h-[92vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{violationType ? 'Edit Violation Type' : 'Add Violation Type'}</DialogTitle>
          <DialogDescription>Define a violation category, cure timeline, stages, and per-stage letter templates.</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="space-y-2"><Label>Category / Name *</Label><Input value={formData.category} onChange={(e) => setFormData(p => ({...p, category: e.target.value}))} placeholder="e.g. Landscaping Non-compliance" required /></div>
          <div className="space-y-2"><Label>Article / Section</Label><Input value={formData.article_section} onChange={(e) => setFormData(p => ({...p, article_section: e.target.value}))} placeholder="e.g. Article V, Section 3" /></div>
          <div className="space-y-2"><Label>Citation</Label><Textarea value={formData.citation} onChange={(e) => setFormData(p => ({...p, citation: e.target.value}))} placeholder="Relevant CC&R language" rows={3} /></div>
          <div className="space-y-2"><Label>Requested Action</Label><Textarea value={formData.requested_action} onChange={(e) => setFormData(p => ({...p, requested_action: e.target.value}))} placeholder="Standard remedy required" rows={3} /></div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Days until violation expires</Label>
              <Input type="number" min={1} value={formData.cure_days} onChange={(e) => setFormData(p => ({...p, cure_days: e.target.value}))} />
              <p className="text-xs text-muted-foreground">Used to calculate the due date when generating notices.</p>
            </div>
            <div className="space-y-2">
              <Label>Number of stages</Label>
              <Select value={String(stageCount)} onValueChange={(v) => setFormData(p => ({...p, stage_count: parseInt(v, 10)}))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">1 stage</SelectItem>
                  <SelectItem value="2">2 stages</SelectItem>
                  <SelectItem value="3">3 stages</SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground">How many notices this violation can escalate through.</p>
            </div>
          </div>

          <div className="space-y-3 border-t pt-4">
            <div className="flex items-start justify-between gap-3 flex-wrap">
              <div>
                <Label className="text-base">Letter Templates</Label>
                <p className="text-xs text-muted-foreground">
                  Customize the body paragraph used in generated notices for each stage. Leave blank to use the system default.
                </p>
              </div>
              <Button type="button" variant="outline" size="sm" onClick={() => setPreviewMode(p => !p)}>
                {previewMode ? <><Pencil className="w-3.5 h-3.5 mr-1.5" /> Edit</> : <><Eye className="w-3.5 h-3.5 mr-1.5" /> Preview</>}
              </Button>
            </div>

            <Tabs value={activeStage} onValueChange={setActiveStage}>
              <TabsList className="w-full justify-start">
                {visibleStages.map((stage) => (
                  <TabsTrigger key={stage} value={stage} className="text-xs">
                    {stage}
                    {formData.letter_templates[stage]?.trim() ? (
                      <span className="ml-1.5 inline-block w-1.5 h-1.5 rounded-full bg-primary" />
                    ) : null}
                  </TabsTrigger>
                ))}
              </TabsList>

              {visibleStages.map((stage) => {
                const value = formData.letter_templates[stage] || '';
                const effective = value.trim() ? value : DEFAULT_TEMPLATES[stage];
                const isCustom = !!value.trim();
                return (
                  <TabsContent key={stage} value={stage} className="space-y-3 mt-3">
                    <div className="flex items-center justify-between gap-2 flex-wrap">
                      <Badge variant={isCustom ? 'default' : 'secondary'} className="text-[10px]">
                        {isCustom ? 'Custom template' : 'Using system default'}
                      </Badge>
                      <div className="flex gap-1.5">
                        <Button type="button" variant="outline" size="sm" onClick={() => loadDefault(stage)}>
                          <RotateCcw className="w-3 h-3 mr-1" /> Load default
                        </Button>
                        {isCustom && (
                          <Button type="button" variant="ghost" size="sm" onClick={() => clearStage(stage)}>
                            Reset to default
                          </Button>
                        )}
                      </div>
                    </div>

                    {!previewMode && (
                      <div className="space-y-2">
                        <div className="flex flex-wrap gap-1.5">
                          <span className="text-xs text-muted-foreground self-center mr-1">Insert:</span>
                          {VARIABLES.map(v => (
                            <Button
                              key={v.key}
                              type="button"
                              variant="outline"
                              size="sm"
                              className="h-6 px-2 text-[11px] font-mono"
                              onClick={() => insertVariable(stage, v.key)}
                            >
                              {`{{${v.key}}}`}
                            </Button>
                          ))}
                        </div>
                        <Textarea
                          ref={(el) => { textareaRefs.current[stage] = el; }}
                          rows={10}
                          placeholder={DEFAULT_TEMPLATES[stage]}
                          value={value}
                          onChange={(e) => setStageTemplate(stage, e.target.value)}
                          className="font-mono text-sm leading-relaxed"
                        />
                        <p className="text-[11px] text-muted-foreground">
                          Variables: {VARIABLES.map(v => <code key={v.key} className="mx-0.5">{`{{${v.key}}}`}</code>)}
                        </p>
                      </div>
                    )}

                    {previewMode && (
                      <div className="rounded-md border bg-muted/40 p-4 text-sm leading-relaxed whitespace-pre-wrap">
                        {fillPreview(effective)}
                        <p className="mt-3 text-[11px] text-muted-foreground italic">
                          Preview shown with sample data: {VARIABLES.map(v => `${v.label} = "${v.sample}"`).join(' • ')}
                        </p>
                      </div>
                    )}
                  </TabsContent>
                );
              })}
            </Tabs>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={loading}>{loading ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Saving...</> : violationType ? 'Update' : 'Create'}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
